<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Kedar Makode - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Kedar Makode - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 16 Jun 2026 21:34:56 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Kedar98/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ AWS EC2: How to Quickly Host Your Website with User Data Scripts ]]>
                </title>
                <description>
                    <![CDATA[ If you want to practice and improve your web hosting skills, this tutorial is for you. With AWS EC2 and a little magic called user data scripts, you’ll be running a stunning website with a CSS template in no time. And the best part? You don’t need to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/aws-ec2-how-to-host-a-website-with-user-data-scripts/</link>
                <guid isPermaLink="false">67462204c9e1cbc5414b4e0c</guid>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ec2 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hosting ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Tue, 26 Nov 2024 19:31:16 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732639814571/62719c49-cd15-4f2c-9586-22a5a300bc4a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to practice and improve your web hosting skills, this tutorial is for you. With AWS EC2 and a little magic called user data scripts, you’ll be running a stunning website with a CSS template in no time. And the best part? You don’t need to manually install everything – the user data script does all the heavy lifting for you.</p>
<p>Before getting started with this guide, make sure you've read through my <a target="_blank" href="https://www.freecodecamp.org/news/host-a-website-on-aws-ec2-using-a-css-template">previous tutorial</a> on AWS EC2. It covers the essentials of creating and configuring an EC2 instance. You'll learn how to navigate the AWS Management Console, select the right instance type, configure security groups, and more.</p>
<p>This foundational knowledge will make sure you're fully prepared to launch your website effortlessly with the help of user data scripts.</p>
<p>So, grab a coffee, and let’s dive into this fun and simple guide. By the end, you’ll be able to launch your own website without breaking a sweat.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-well-cover">What We'll Cover</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-launch-your-ec2-instance">Step 1: Launch Your EC2 Instance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-wait-the-script-did-everything-already">Step 2: Wait… The Script Did Everything Already?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-access-your-website">Step 3: Access Your Website</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-want-more">Want more?</a></p>
</li>
</ul>
<h2 id="heading-what-well-cover">What We’ll Cover:</h2>
<p>Today, we’re going to:</p>
<ul>
<li><p>Launch an EC2 instance (Don’t worry, it’s easier than it sounds).</p>
</li>
<li><p>Use a user data script to automate setting up a web server.</p>
</li>
<li><p>Download a CSS template and host it on your instance.</p>
</li>
</ul>
<p>You might be wondering: why a user data script? Imagine it as a to-do list for your EC2 instance. When the instance boots up, it runs through this list and sets everything up automatically. It’s like having a personal assistant that handles all the tedious setup tasks. Sounds good, right?</p>
<h3 id="heading-step-1-launch-your-ec2-instance">Step 1: Launch Your EC2 Instance</h3>
<p>First things first, head over to your AWS Management Console. This is where all the magic happens.</p>
<p>Log in to AWS and head to the AWS Console. If you don’t already have an account, don’t worry, you can just sign up – it's free for basic usage.</p>
<p>Now here are the steps you’ll follow to launch the instance:</p>
<ul>
<li><p>In the console, type <strong>EC2</strong> in the search bar and click on the EC2 service.</p>
</li>
<li><p>Click the big <strong>Launch Instance</strong> button.</p>
</li>
<li><p>Give your instance a cool <strong>name</strong> like "Webserver".</p>
</li>
<li><p><strong>Choose Your AMI</strong>: Select the Amazon Linux 2 AMI (free-tier eligible). It’s lightweight, fast, and perfect for our use case.</p>
</li>
<li><p><strong>Instance Type</strong>: Go for the t2.micro (it’s free for most use cases, and we love free things, right?).</p>
</li>
<li><p><strong>User Data Script</strong>: Now, this is where things get good. Scroll down to Advanced Details, and in the User Data field, paste in the following script. This script will handle everything from installing Apache to downloading and unzipping a fancy CSS template.</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732640127024/ec187a49-61ac-4a98-82c1-c149bcf8ef91.png" alt="user data script" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-bash">  <span class="hljs-comment">#!/bin/bash</span>

  <span class="hljs-comment"># Update the instance and install necessary packages</span>
  yum update -y
  yum install -y httpd wget unzip

  <span class="hljs-comment"># Start Apache and enable it to start on boot</span>
  systemctl start httpd
  systemctl <span class="hljs-built_in">enable</span> httpd

  <span class="hljs-comment"># Navigate to the web root directory</span>
  <span class="hljs-built_in">cd</span> /var/www/html

  <span class="hljs-comment"># Download a CSS template directly</span>
  wget https://www.free-css.com/assets/files/free-css-templates/download/page284/built-better.zip

  <span class="hljs-comment"># Unzip the template and move the files to the web root</span>
  unzip built-better.zip -d /var/www/html/
  mv /var/www/html/html/* /var/www/html/

  <span class="hljs-comment"># Clean up unnecessary files</span>
  rm -r /var/www/html/html
  rm built-better.zip

  <span class="hljs-comment"># Restart Apache to apply changes</span>
  systemctl restart httpd
</code></pre>
<ul>
<li><strong>Configure Your Security Group</strong>: You want the world to be able to see your site, right? So, make sure to allow <strong>HTTP</strong> (port 80). This will let your website be accessible to anyone with the link.</li>
</ul>
</li>
</ul>
<ul>
<li><strong>Launch Your Instance</strong>: After double-checking everything, click <strong>Launch</strong>. AWS will ask you to choose a key pair (which you’ll need if you want to SSH into your instance later). If you don’t have one, create a new key pair.</li>
</ul>
<p>    Boom! Your EC2 instance is launching. Grab a snack, it’ll be ready in a few minutes.</p>
<h3 id="heading-step-2-waitthe-script-did-everything-already">Step 2: Wait…The Script Did Everything Already?</h3>
<p>Yes, that’s right! Thanks to the user data script, all the heavy lifting is done for you.</p>
<p>Here’s what just happened behind the scenes:</p>
<ul>
<li><p>Apache Web Server was installed and started.</p>
</li>
<li><p>A CSS template called “Built Better” was downloaded directly into the server.</p>
</li>
<li><p>The template was unzipped and placed in the web directory.</p>
</li>
</ul>
<p>All of this happened while you were sipping your coffee.</p>
<h3 id="heading-step-3-access-your-website">Step 3: Access Your Website</h3>
<p>The exciting part is finally here! Let’s see your website in action.</p>
<ul>
<li><p>Find Your Instance’s Public IP:</p>
<ul>
<li><p>Head to your EC2 Dashboard, and you’ll see your running instance.</p>
<p>  Copy the Public IPv4 Address.</p>
</li>
</ul>
</li>
<li><p>Open Your Browser:</p>
<ul>
<li><p>In the address bar, type: <code>http://your-public-ip</code> (replace <code>your-public-ip</code> with the one you just copied).</p>
</li>
<li><p>Hit enter, and… <strong>Voilà!</strong> Your website is live, looking all professional with the “Built Better” CSS template.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Let’s take a moment to appreciate what you’ve accomplished:</p>
<ul>
<li><p>Launched an EC2 instance ✔️</p>
</li>
<li><p>Automated the setup using a user data script ✔️</p>
</li>
<li><p>Hosted a slick website using a CSS template ✔️</p>
</li>
</ul>
<p>You’ve just dipped your toes into the world of AWS and cloud hosting. It’s not as intimidating as it sounds, right? If you enjoyed this, keep exploring AWS – the possibilities are endless. Until next time, happy coding and hosting!</p>
<h3 id="heading-want-more">Want more?</h3>
<p>Follow me on Twitter or connect on LinkedIn for more awesome cloud tips and tricks. I’m always sharing helpful content and would love to hear about your cloud journey!</p>
<p>You can follow me on</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Introduction to Docker and Containers for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In the world of modern software development, efficiency and consistency are key. Developers and operations teams need solutions that help them manage, deploy, and run applications seamlessly across different environments. Containers and Docker are te... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-docker-and-containers-for-beginners/</link>
                <guid isPermaLink="false">6745acca09ace2d743c17be9</guid>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ containers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Tue, 26 Nov 2024 11:11:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731093934598/6f2fa740-63e6-48e9-8e17-364544d1fcc6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the world of modern software development, efficiency and consistency are key. Developers and operations teams need solutions that help them manage, deploy, and run applications seamlessly across different environments.</p>
<p>Containers and Docker are technologies that have revolutionized how software is built, tested, and deployed.</p>
<p>Whether you're new to the world of tech or just looking to understand the basics of Docker, this article will guide you through the essentials.</p>
<h2 id="heading-table-of-content">Table of Content</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-containers">What Are Containers?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-docker">What is Docker?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-docker">Why Docker?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-docker-architecture">Docker Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dockers-container-runtime-containerd">Docker’s Container Runtime: containerd</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-simple-container-using-docker">How to Create a Simple Container Using Docker</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-what-are-containers">What Are Containers?</h2>
<p>Before diving into Docker, let’s first understand containers. Imagine that you’re working on a project, and your application works perfectly on your laptop. But when you try to run the same application on a different machine, it fails. This is often due to differences in environments: different operating systems, installed software versions, or configurations.</p>
<p>Containers solve this problem by packaging an application and all its dependencies like libraries, frameworks, and configuration files into a single, standardized unit. This ensures that the application runs the same no matter where it's deployed, whether on your laptop, a server, or in the cloud.</p>
<p>Key features of containers:</p>
<ul>
<li><p><strong>Lightweight</strong>: Containers share the host system's kernel, unlike virtual machines (VMs) that require separate OS instances, making them faster and more efficient.</p>
</li>
<li><p><strong>Portable</strong>: Once built, a container can run consistently across various environments.</p>
</li>
<li><p><strong>Isolated</strong>: Containers run in isolated processes, meaning that they don’t interfere with other applications running on the same system.</p>
</li>
</ul>
<h2 id="heading-what-is-docker">What is Docker?</h2>
<p>Now that we understand containers, let’s talk about Docker, the platform that has made containers mainstream.</p>
<p>Docker is an open-source tool designed to simplify the process of creating, managing, and deploying containers. Launched in 2013, Docker has rapidly become the go-to solution for containerization due to its ease of use, community support, and powerful ecosystem of tools.</p>
<h3 id="heading-key-concepts-in-docker">Key Concepts in Docker</h3>
<ol>
<li><p><strong>Docker Images</strong>: Think of a Docker image as a blueprint for your container. It contains everything needed to run the application, including code, libraries, and system dependencies. Images are built from a set of instructions written in a Dockerfile.</p>
</li>
<li><p><strong>Docker Containers</strong>: A container is a running instance of a Docker image. When you create and start a container, Docker launches the image into an isolated environment where your application can run.</p>
</li>
<li><p><strong>Dockerfile</strong>: This is a text file that contains the steps needed to create a Docker image. It’s where you define what your container will look like, including the base image, application code, and any additional dependencies.</p>
</li>
<li><p><strong>Docker Hub</strong>: Docker Hub is a public registry where developers can share and access pre-built images. If you're working on a common application or technology stack, chances are that there’s already an image available on Docker Hub, saving you time.</p>
</li>
<li><p><strong>Docker Compose</strong>: For applications that require multiple containers (for example, a web server and a database), Docker Compose allows you to define and manage multi-container environments using a simple YAML file.</p>
</li>
</ol>
<h2 id="heading-why-docker">Why Docker?</h2>
<p>Docker's popularity stems from its ability to solve a variety of challenges developers face today:</p>
<ul>
<li><p><strong>Consistency Across Environments</strong>: Developers can "build once, run anywhere," ensuring the same application works the same way in different environments, from local development to production.</p>
</li>
<li><p><strong>Speed</strong>: Docker containers are fast to start and stop, making them ideal for testing and deployment pipelines.</p>
</li>
<li><p><strong>Efficient Use of Resources</strong>: Since containers share the host system's resources more effectively than virtual machines, they reduce overhead and allow for greater density in deployments.</p>
</li>
<li><p><strong>Version Control for Your Applications</strong>: Docker allows you to version control not only your code but also the environment in which your code runs. This is particularly useful for rolling back to previous versions or debugging issues in production.</p>
</li>
</ul>
<h2 id="heading-docker-architecture">Docker Architecture</h2>
<p>When you first start using Docker, you may treat it as a box that "just works." While that’s fine for getting started, a deeper understanding of Docker’s architecture will help you troubleshoot issues, optimize performance, and make informed decisions about your containerization strategy.</p>
<p>Docker's architecture is designed to ensure efficiency, flexibility, and scalability. It’s composed of several components that work together to create, manage, and run containers. Let’s take a closer look at each of these components.</p>
<h3 id="heading-docker-architecture-key-components">Docker Architecture: Key Components</h3>
<p>Docker’s architecture is built around a client-server model that includes the following components</p>
<ul>
<li><p><strong>Docker Client</strong></p>
</li>
<li><p><strong>Docker Daemon (dockerd)</strong></p>
</li>
<li><p><strong>Docker Engine</strong></p>
</li>
<li><p><strong>Docker Images</strong></p>
</li>
<li><p><strong>Docker Containers</strong></p>
</li>
<li><p><strong>Docker Registries</strong></p>
</li>
</ul>
<p><img src="https://docs.docker.com/get-started/images/docker-architecture.webp" alt="Docker Architecture" width="600" height="400" loading="lazy"></p>
<h4 id="heading-1-docker-client">1. Docker Client</h4>
<p>The Docker Client is the primary way users interact with Docker. It’s a command-line tool that sends instructions to the Docker Daemon (which we’ll cover next) using REST APIs. Commands like <code>docker build</code>, <code>docker pull</code>, and <code>docker run</code> are executed from the Docker Client.</p>
<p>When you type a command like <code>docker run nginx</code>, the Docker Client translates that into a request that the Docker Daemon can understand and act upon. Essentially, the Docker Client acts as a front-end for interacting with Docker’s more complex backend components.</p>
<h4 id="heading-2-docker-daemon-dockerd">2. Docker Daemon (dockerd)</h4>
<p>The Docker Daemon, also known as <strong>dockerd</strong>, is the brain of the entire Docker operation. It’s a background process that listens for requests from the Docker Client and manages Docker objects like containers, images, networks, and volumes.</p>
<p>Here’s what the Docker Daemon is responsible for</p>
<ul>
<li><p><strong>Building and running containers</strong>: When the client sends a command to run a container, the daemon pulls the image, creates the container, and starts it.</p>
</li>
<li><p><strong>Managing Docker resources</strong>: The daemon handles tasks like network configurations and volume management.</p>
</li>
</ul>
<ul>
<li>The Docker Daemon runs on the host machine and communicates with the Docker Client using a REST API, Unix sockets, or a network interface. It’s also responsible for interacting with container runtimes, which handle the actual execution of containers.</li>
</ul>
<h4 id="heading-3-docker-engine">3. Docker Engine</h4>
<p>The Docker Engine is the core part of Docker. It’s what makes the entire platform work, combining the client, daemon, and container runtime. Docker Engine can run on various operating systems, including Linux, Windows, and macOS.</p>
<p>There are two versions of the Docker Engine</p>
<ul>
<li><p><strong>Docker CE (Community Edition)</strong>: This is the free, open-source version of Docker that’s widely used for personal and smaller-scale projects.</p>
</li>
<li><p><strong>Docker EE (Enterprise Edition)</strong>: The paid, enterprise-level version of Docker comes with additional features like enhanced security, support, and certification.</p>
</li>
</ul>
<p>The Docker Engine simplifies the complexities of container orchestration by integrating the various components required to build, run, and manage containers.</p>
<h4 id="heading-4-docker-images">4. Docker Images</h4>
<p>A Docker Image is a read-only template that contains everything your application needs to run—code, libraries, dependencies, and configurations. Images are the building blocks of containers. When you run a container, you are essentially creating a writable layer on top of a Docker image.</p>
<p>Docker Images are typically built from Dockerfiles, which are text files that contain instructions on how to build the image. For example, a basic Dockerfile might start with a base image like <code>nginx</code> or <code>ubuntu</code> and include commands to copy files, install dependencies, or set environment variables.</p>
<p>Here’s a simple example of a Dockerfile</p>
<pre><code class="lang-bash">dockerfileCopy codeFROM nginx:latest
COPY ./html /usr/share/nginx/html
EXPOSE 80
</code></pre>
<p>In this example, we’re using the official Nginx image as the base and copying our local HTML files into the container’s web directory.</p>
<p>Once the image is built, it can be stored in a Docker Registry and shared with others.</p>
<h4 id="heading-5-docker-containers">5. Docker Containers</h4>
<p>A Docker Container is a running instance of a Docker Image. It’s lightweight and isolated from other containers, yet it shares the kernel of the host operating system. Each container has its own file system, memory, CPU allocation, and network settings, which makes it portable and reproducible.</p>
<p>Containers can be created, started, stopped, and destroyed, and they can even be persisted between reboots. Because containers are based on images, they ensure that applications will behave the same way no matter where they’re run.</p>
<p>A few key characteristics of Docker containers:</p>
<ul>
<li><p><strong>Isolation</strong>: Containers are isolated from each other and the host, but they still share the same OS kernel.</p>
</li>
<li><p><strong>Portability</strong>: Containers can run anywhere, whether on your local machine, a virtual machine, or a cloud provider.</p>
</li>
</ul>
<h4 id="heading-6-docker-registries">6. Docker Registries</h4>
<p>A Docker Registry is a centralized place where Docker Images are stored and distributed. The most popular registry is Docker Hub, which hosts millions of publicly available images. Organizations can also set up private registries to store and distribute their own images securely.</p>
<p>Docker Registries provide several key features:</p>
<ul>
<li><p><strong>Image Versioning</strong>: Images are versioned using tags, making it easy to manage different versions of an application.</p>
</li>
<li><p><strong>Access Control</strong>: Registries can be public or private, with role-based access control to manage who can pull or push images.</p>
</li>
<li><p><strong>Distribution</strong>: Images can be pulled from a registry and deployed anywhere, making it easy to share and reuse containerized applications.</p>
</li>
</ul>
<h2 id="heading-dockers-container-runtime-containerd">Docker’s Container Runtime: containerd</h2>
<p>One important recent development in Docker’s architecture is the use of containerd. Docker used to have its own container runtime, but now it uses containerd, a container runtime that follows industry standards and is also used by other platforms like Kubernetes.</p>
<ol>
<li><p>containerd is responsible for</p>
<ul>
<li><p>Starting and stopping containers</p>
</li>
<li><p>Managing storage and networking for containers</p>
</li>
<li><p>Pulling container images from registries</p>
</li>
</ul>
</li>
</ol>
<p>By separating the container runtime from Docker’s higher-level functionality, Docker has become more modular, allowing other tools to use containerd while Docker focuses on user-facing features.</p>
<h2 id="heading-how-to-create-a-simple-container-using-docker">How to Create a Simple Container Using Docker</h2>
<p><strong>Pull the Linux Image</strong></p>
<p>Start by pulling the <code>alpine</code> image from Docker Hub. The <code>alpine</code> image is a minimal Linux distribution, designed to be lightweight and fast.</p>
<p>Run the following command:</p>
<pre><code class="lang-bash">docker pull alpine
</code></pre>
<p>This will download the <code>alpine</code> image to your local system.</p>
<p><strong>Run the Container</strong></p>
<p>Create and start a container using the <code>alpine</code> image. We’ll also launch a terminal session inside the container.</p>
<pre><code class="lang-bash">docker run -it alpine /bin/sh
</code></pre>
<p>Here’s what each option means:</p>
<ul>
<li><p><code>docker run</code>: Creates and starts a new container.</p>
</li>
<li><p><code>-it</code>: Allows you to interact with the container (interactive mode + terminal).</p>
</li>
<li><p><code>alpine</code>: Specifies the image to use.</p>
</li>
<li><p><code>/bin/sh</code>: Specifies the command to run inside the container (a shell session in this case).</p>
</li>
</ul>
<p><strong>Explore the Container</strong></p>
<p>Once the container is running, you’ll see a shell prompt that looks something like this</p>
<pre><code class="lang-bash">/ <span class="hljs-comment">#</span>
</code></pre>
<p>This indicates you are inside the Alpine Linux container. You can now run Linux commands. For example:</p>
<p>Check the current directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
</code></pre>
<p>List files in the directory:</p>
<pre><code class="lang-bash">ls
</code></pre>
<p>Output: A minimal directory structure, as Alpine is a lightweight image.</p>
<p>You can also install a package (Alpine uses <code>apk</code> as its package manager):</p>
<pre><code class="lang-bash">apk add curl
</code></pre>
<p><strong>Exit the Container</strong></p>
<p>When you're done exploring, type <code>exit</code> to close the session and stop the container</p>
<pre><code class="lang-bash">bashCopy codeexit
</code></pre>
<p><strong>Access the Container After It’s Stopped</strong></p>
<p>If you want to access the container again after stopping it, you can use this command to list all containers (including stopped ones):</p>
<pre><code class="lang-bash">docker ps -a
</code></pre>
<p>You’ll see a list of containers with their IDs and statuses, then you can start the stopped container:</p>
<pre><code class="lang-bash">docker start &lt;container-id&gt;
</code></pre>
<p>You can attach to the container's shell using this command:</p>
<pre><code class="lang-bash">docker <span class="hljs-built_in">exec</span> -it &lt;container-id&gt; /bin/sh
</code></pre>
<p>If you no longer need the container, you can remove it</p>
<ol>
<li><p>Stop the container (if it’s still running):</p>
<pre><code class="lang-bash"> docker stop &lt;container-id&gt;
</code></pre>
</li>
<li><p>Remove the container:</p>
<pre><code class="lang-bash"> docker rm &lt;container-id&gt;
</code></pre>
</li>
</ol>
<p><strong>Key Docker Commands Recap</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Command</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>docker pull alpine</code></td><td>Downloads the Alpine Linux image.</td></tr>
<tr>
<td><code>docker run -it alpine /bin/sh</code></td><td>Creates and starts an interactive container.</td></tr>
<tr>
<td><code>docker ps -a</code></td><td>Lists all containers (running and stopped).</td></tr>
<tr>
<td><code>docker start &lt;container-id&gt;</code></td><td>Starts a stopped container.</td></tr>
<tr>
<td><code>docker exec -it &lt;container-id&gt;</code></td><td>Attaches to a running container.</td></tr>
<tr>
<td><code>docker stop &lt;container-id&gt;</code></td><td>Stops a running container.</td></tr>
<tr>
<td><code>docker rm &lt;container-id&gt;</code></td><td>Removes a stopped container.</td></tr>
</tbody>
</table>
</div><h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Now that you've got a foundational understanding, it's time to put your knowledge to use. Start experimenting with Docker, build your first container, and explore its vast ecosystem.</p>
<p>You'll soon see why Docker has become a cornerstone of modern DevOps and software engineering.</p>
<p>You can follow me on</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Host a Website on AWS EC2 Using a CSS Template ]]>
                </title>
                <description>
                    <![CDATA[ Are you ready to take your web hosting skills to the next level by using a CSS template? Hosting a professional looking website doesn’t have to be complicated, and with AWS EC2, you can have your website live in no time! In this guide, I’ll show you ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/host-a-website-on-aws-ec2-using-a-css-template/</link>
                <guid isPermaLink="false">672e5a06d7a5828f344ec242</guid>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ec2 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 08 Nov 2024 18:35:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731103973241/e1277a4c-3456-4f11-b809-24caf56ae13a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you ready to take your web hosting skills to the next level by using a CSS template? Hosting a professional looking website doesn’t have to be complicated, and with AWS EC2, you can have your website live in no time!</p>
<p>In this guide, I’ll show you how to host a website using a pre-designed template from <a target="_blank" href="https://www.free-css.com/free-css-templates"><strong>CSS templates</strong></a> directly on your EC2 instance.</p>
<p>Before we dive into this guide, make sure you’ve gone through my <a target="_blank" href="https://www.freecodecamp.org/news/how-to-launch-an-ec2-instance-and-a-web-server-using-httpd/"><strong>previous blog</strong></a> on how to launch and connect to an EC2 instance. If you haven’t set up an EC2 instance yet, head over to that post first to get your instance up and running. Once that’s done, you’re all set to proceed!</p>
<h3 id="heading-step-1-download-the-built-better-template">Step 1: Download the "Built Better" Template</h3>
<p>For this tutorial, we’ll use the Built Better template, which is free and easy to set up.</p>
<p>Head over to <a target="_blank" href="https://www.free-css.com/free-css-templates/page284/built-better">this link</a> and download the template.</p>
<p>Right-click on the download button and select "Copy clean link". We’ll use this link to download the template directly into your EC2 instance.</p>
<h3 id="heading-step-2-download-the-template-directly-to-your-ec2-instance">Step 2: Download the Template Directly to Your EC2 Instance</h3>
<p>Now that you have the link to the template, let’s download it straight to your EC2 instance using <code>wget</code>.</p>
<p>Log in to your EC2 instance via SSH or MobaXterm (as covered in my <a target="_blank" href="https://www.freecodecamp.org/news/connect-to-your-ec2-instance-using-mobaxterm/"><strong>previous blog</strong></a>) and navigate to the <code>/var/www/html</code> directory where your website files will be stored:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> /var/www/html
</code></pre>
<p>Use the <code>wget</code> command followed by the copied link to download the "Built Better" template directly into your EC2 instance:</p>
<pre><code class="lang-bash">sudo wget https://www.free-css.com/assets/files/free-css-templates/download/page284/built-better.zip
</code></pre>
<p><strong>Note:</strong> After downloading, it's a good idea to check the file name to ensure it matches the file used in the subsequent commands. You can do this by running the <code>ls</code> command:</p>
<pre><code class="lang-bash">ls
</code></pre>
<h3 id="heading-step-3-unzip-the-template-files">Step 3: Unzip the Template Files</h3>
<p>Now that the template has been downloaded, it’s time to extract it. Install the <code>unzip</code> utility if it’s not already installed:</p>
<pre><code class="lang-bash">sudo dnf install unzip -y
</code></pre>
<p>Then unzip the template:</p>
<pre><code class="lang-bash">sudo unzip built-better.zip -d /var/www/html/
</code></pre>
<p>After unzipping, make sure to check the folder name where the files were extracted from. You can do this by listing the contents of the <code>/var/www/html</code> directory:</p>
<pre><code class="lang-bash">ls /var/www/html/
</code></pre>
<p>In this case, the unzipped contents are located inside a folder named <code>html</code>. This folder contains all the template files. If the folder name is different in your case, adjust the following steps accordingly.</p>
<p>First, move the files from the <code>html</code> folder to the root <code>/var/www/html/</code> directory:</p>
<pre><code class="lang-bash">sudo mv /var/www/html/html/* /var/www/html/
</code></pre>
<p>Then remove the unnecessary folder:</p>
<pre><code class="lang-bash">sudo rm -r /var/www/html/html
</code></pre>
<p>Lastly, remove the ZIP file:</p>
<pre><code class="lang-bash">sudo rm built-better.zip
</code></pre>
<h3 id="heading-step-4-set-up-the-web-server-to-host-your-template">Step 4: Set Up the Web Server to Host Your Template</h3>
<p>If you haven’t already, make sure your Apache HTTPD web server is installed and running. You can follow these steps to ensure your server is ready:</p>
<p>Install Apache (if not installed):</p>
<pre><code class="lang-bash">sudo yum install httpd -y
</code></pre>
<p>Start the Apache service:</p>
<pre><code class="lang-bash">sudo systemctl start httpd
</code></pre>
<p>Enable Apache to start on boot:</p>
<pre><code class="lang-bash">sudo systemctl <span class="hljs-built_in">enable</span> httpd
</code></pre>
<p>Now your web server should be up and running, ready to serve your template.</p>
<h3 id="heading-step-5-test-your-website">Step 5: Test Your Website</h3>
<p>Now for the exciting part seeing your site live! Open a browser and navigate to your EC2 instance’s public IP address. You should now see the Built Better template live and ready to go.</p>
<p>Here’s how to check:</p>
<ul>
<li><p>Find your EC2 instance’s public IP from the AWS EC2 dashboard.</p>
</li>
<li><p>Enter the IP in your browser, like so: <a target="_blank" href="http://your-ec2-public-ip"><code>http://your-ec2-public-ip</code></a></p>
</li>
<li><p>Your website should now be live with the Built Better template! 🎉</p>
</li>
</ul>
<h3 id="heading-wrapping-up">Wrapping Up</h3>
<p>Congratulations! You’ve successfully hosted a professional-looking website using the Built Better CSS template on your EC2 instance.</p>
<p>With just a few steps, you’ve moved from launching an EC2 instance to hosting a fully styled website, all using the AWS powerful cloud infrastructure.</p>
<p>You can follow me on</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Launch an EC2 Instance and Set Up a Web Server Using HTTPD ]]>
                </title>
                <description>
                    <![CDATA[ Hey there! Have you ever thought about creating your own web server on the cloud? Well, you’re in for a treat because in this article, we’re going to explore how you can launch an EC2 instance and use HTTPD to host a simple web server. Don’t worry – ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-launch-an-ec2-instance-and-a-web-server-using-httpd/</link>
                <guid isPermaLink="false">672a1e5f52317a5d102c0dd9</guid>
                
                    <category>
                        <![CDATA[ ec2 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ apache ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Tue, 05 Nov 2024 13:32:15 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730780706184/e2ac9a27-7221-47c6-a8ae-db2f62892036.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hey there! Have you ever thought about creating your own web server on the cloud? Well, you’re in for a treat because in this article, we’re going to explore how you can launch an EC2 instance and use HTTPD to host a simple web server.</p>
<p>Don’t worry – it’s simpler than it sounds, and I promise to walk you through it step-by-step with a bit of fun along the way.</p>
<p>By the end of this guide, you’ll feel like a cloud wizard, casting spells that make servers appear out of thin air (well, out of Amazon’s data centers, but you get the point).</p>
<p>Ready? Let’s dive in!</p>
<h2 id="heading-table-of-content">Table Of Content</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-ec2">What Is EC2?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-httpd">What is HTTPD?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-how-to-launch-your-ec2-instance">Step 1: How to Launch Your EC2 Instance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-how-to-connect-to-your-ec2-instance">Step 2: How to Connect to Your EC2 Instance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-how-to-install-and-start-httpd-apache-web-server">Step 3: How to Install and Start HTTPD (Apache Web Server)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-how-to-host-your-custom-web-page">Step 4: How to Host Your Custom Web Page</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-what-is-ec2">What Is EC2?</h2>
<p>Think of EC2 (Elastic Compute Cloud) as a hotel room in the cloud. Instead of booking a physical server to store your website, you’re renting one from Amazon’s magical cloud infrastructure. This room (or instance) comes with all the amenities you need to host a website. Today, we’ll install <strong>HTTPD</strong> (a web server software) in our “room” to make our website live. 🏨✨</p>
<h2 id="heading-what-is-httpd">What is HTTPD?</h2>
<ul>
<li><p>At its core, HTTPD stands for Hypertext Transfer Protocol Daemon. Let’s break that down:</p>
</li>
<li><p><strong>Hypertext Transfer Protocol (HTTP)</strong>: This is the standard protocol used on the web. When you type a URL into your browser or click a link, you’re using HTTP to tell the server, “Hey, send me this web page!”</p>
</li>
<li><p><strong>Daemon (D)</strong>: A daemon is just a fancy term for a background process that runs continuously on a server. In this case, the daemon is responsible for responding to requests from web browsers (like Chrome or Firefox) and sending back the appropriate content.</p>
</li>
<li><p>So, <strong>HTTPD</strong> is a program that listens for incoming HTTP requests (like when you visit a webpage) and serves back the data (HTML, CSS, images, and so on) needed to display that page.</p>
</li>
</ul>
<h4 id="heading-httpd-vs-apache2-different-names-same-game">HTTPD vs. Apache2: Different Names, Same Game</h4>
<p>Depending on your Linux distribution, you may encounter different names for the same basic software:</p>
<ul>
<li><p>On RPM-based distributions (like Red Hat, CentOS, or Fedora), it’s called httpd.</p>
</li>
<li><p>On Debian-based distributions (like Ubuntu or Debian itself), it’s referred to as apache2.</p>
</li>
</ul>
<p>Let’s look at the steps you can use to launch your EC2 instance, and how to set up a web server using HTTPD.</p>
<h2 id="heading-step-1-how-to-launch-your-ec2-instance">Step 1: How to Launch Your EC2 Instance</h2>
<p>First things first, let’s launch our EC2 instance. You’ll need an AWS account—signing up is free, and AWS offers a free tier, so this won’t cost you a dime for small-scale experiments.</p>
<p>Head over to the AWS Management Console and log in. From the search bar, type “EC2” and click on <strong>EC2 Dashboard</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730267447129/5460a622-b2de-456a-9fae-b757caf37eef.png" alt="EC2 Dashboard" class="image--center mx-auto" width="1918" height="872" loading="lazy"></p>
<p>Create a new instance by clicking on the orange <strong>Launch Instance</strong> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730345828735/7f2df691-278c-4945-97a6-44e173819eb0.png" alt="Create Instance on AWS" class="image--center mx-auto" width="1918" height="868" loading="lazy"></p>
<p>Next, choose the Amazon Machine Image (AMI) by selecting the Amazon Linux AMI, which is free-tier eligible and super reliable. Don’t forget to give your instance a unique name!</p>
<p>Adding a "Name" tag with a value like "MyFirstInstance" or "ProductionServer" helps you keep track of multiple instances while adding a personal touch to your cloud workspace.</p>
<p>Also, remember to check the default username for the AMI you select. Since you’ve chosen Amazon Linux, the default username is <strong>ec2-user</strong>. Keep this in mind for connecting to your instance later!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346031697/3c707686-c8f9-4cdf-aaec-c369722eaea0.png" alt="Amazon Machine Image (AMI) and Tags (Name)" class="image--center mx-auto" width="1918" height="873" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346255437/478efdf2-70b3-46e0-a0ca-131757929a69.png" alt="Amazon Machine Image (AMI) Default Username" class="image--center mx-auto" width="873" height="767" loading="lazy"></p>
<p><strong>Select an Instance Type</strong>: The t2.micro is your best buddy here again, free-tier eligible and perfect for our needs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346372896/b902fd57-e7e3-4144-9186-832b590b3321.png" alt="Instance Type for EC2" class="image--center mx-auto" width="882" height="322" loading="lazy"></p>
<p><strong>Key Pair for SSH Access</strong>: Here’s where it gets important to have a <strong>.pem</strong> file to securely connect to your instance. This file, also known as a key pair, acts like the secret key to your cloud “hotel room,” allowing you to log in via SSH.</p>
<p>If you already have a <strong>.pem</strong> file for a previously created key pair, go ahead and choose that from the dropdown menu.</p>
<p>If you don’t have a <strong>.pem</strong> file, no worries! Create a new key pair by clicking <strong>Create New Key Pair</strong>, and download the <strong>.pem</strong> file to your computer. Make sure to store this file safely—you’ll need it to log in, and if you lose it, you won’t be able to access your EC2 instance!</p>
<p>Why is this file important? The <strong>.pem</strong> file is your private key, and AWS uses it to verify that you are the rightful owner trying to connect to the instance. You won’t get access without it, just like how you can’t get into a hotel room without the key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346428068/e8d1c913-af2f-40ad-8a80-b2b31af934f4.png" alt="Key Pair for AWS EC2" class="image--center mx-auto" width="882" height="257" loading="lazy"></p>
<p><strong>Configure Security Group</strong>: AWS EC2 security groups are like virtual firewalls that control traffic in and out of your instance, ensuring only specific types of access. To allow web visitors, set up an HTTP rule on port 80, and for secure server logins, enable SSH on port 22 with restricted IPs.</p>
<p>You can reuse security groups across instances, making configuration easier and more consistent. Regularly review these settings to keep your instance secure and organized.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346477838/1b296a9d-ab53-48f6-a92b-07057332eaed.png" alt="Security Group for AWS EC2" class="image--center mx-auto" width="873" height="770" loading="lazy"></p>
<p><strong>Launch the instance</strong>: Boom! You’ve just launched your very own server in the cloud.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730346693723/9aa28c70-8732-4071-ae03-12d983c6cb15.png" alt="Launch AWS EC2 Instance" class="image--center mx-auto" width="1918" height="873" loading="lazy"></p>
<p>Wait a minute or two for your instance to come online. Now that we have our EC2 instance running, let’s move to the next step of `setting up our web server.</p>
<h3 id="heading-step-2-how-to-connect-to-your-ec2-instance">Step 2: How to Connect to Your EC2 Instance</h3>
<p>To connect, we’ll use the <strong>.pem</strong> file (key pair) we created earlier. If you’re on a Mac or Linux machine, this is super simple with SSH. For Windows folks, I recommend using <strong>MobaXterm</strong>—it’s a user-friendly terminal with SSH built-in.</p>
<p>If you’re new to connecting EC2 instances using MobaXterm, I’ve written a detailed guide in my previous blog post. You can check it out <a target="_blank" href="https://www.freecodecamp.org/news/connect-to-your-ec2-instance-using-mobaxterm/">here</a>, where I show how to set up and connect to an EC2 instance using MobaXterm.</p>
<p>For now, here’s a quick overview of the connection process using SSH:</p>
<pre><code class="lang-bash">ssh -i <span class="hljs-string">"your-key.pem"</span> ec2-user@your-ec2-public-ip
</code></pre>
<p>Replace <code>"your-key.pem"</code> with the name of your key pair and <code>"your-ec2-public-ip"</code> with the public IP of your instance (you can find this in the EC2 dashboard).</p>
<p>If you’ve connected successfully, congratulations! 🎉 You’re inside your cloud server.</p>
<h3 id="heading-step-3-how-to-install-and-start-httpd-apache-web-server">Step 3: How to Install and Start HTTPD (Apache Web Server)</h3>
<p>Alright, time to install our web server software (HTTPD)! We’ll be using Apache, one of the most popular web servers around. Don’t worry, you don’t need a degree in IT to get this working.</p>
<p>After you successfully connect to your EC2 instance from MobaXterm, you should be all set to start the installation. You’re just a few commands away from having your web server up and running!</p>
<p>It’s always good practice to make sure your server is up to date. To update your server, run:</p>
<pre><code class="lang-bash">sudo dnf update -y
</code></pre>
<p>Next, we’ll install HTTPD (Apache):</p>
<pre><code class="lang-bash">sudo dnf install httpd -y
</code></pre>
<p>Then start the HTTPD service. Run this command to get the server running.</p>
<pre><code class="lang-bash">sudo systemctl start httpd
</code></pre>
<p>Next, enable it to start on boot so that every time your EC2 instance reboots, your web server comes back to life automatically.</p>
<pre><code class="lang-bash">sudo systemctl <span class="hljs-built_in">enable</span> httpd
</code></pre>
<p>Time to test it out! Open your browser and type in your instance’s public IP. If you see the Apache test page, give yourself a high-five. 🖐️ You’ve just launched a web server!</p>
<h3 id="heading-step-4-how-to-host-your-custom-web-page">Step 4: How to Host Your Custom Web Page</h3>
<p>Now, let’s get creative! Instead of the default web server message, let’s host your very own custom web page in just one step. This will allow you to display a unique message on your site in no time.</p>
<p>Run the following command in your EC2 instance to create and display a simple, personalized web page:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Welcome to the Cloud! You’re now hosting your own custom web server 
using AWS EC2 and Apache!"</span> &gt; /var/www/html/index.html
</code></pre>
<p><strong>What does this command do?</strong></p>
<ul>
<li><p>The <code>echo</code> command outputs the text: <code>"Welcome to the Cloud! You’re now hosting your own custom web server using AWS EC2 and Apache!"</code>.</p>
</li>
<li><p>The <code>&gt;</code> symbol redirects this output to a file.</p>
</li>
<li><p><code>/var/www/html/index.html</code> is the path to the file where the message is saved. This file is the homepage of your web server.</p>
</li>
</ul>
<p>By running this command, you're replacing the default Apache test page with your custom message.</p>
<p>Now, select your EC2 instance, and you’ll find its public IP address. Open your browser, enter that IP, refresh the page, and boom! Your custom message is live on the site. 🎉</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347026257/8ae32095-27f2-401a-a812-12b1354c3a93.png" alt="EC2 Instance Public IP Address" class="image--center mx-auto" width="1918" height="870" loading="lazy"></p>
<p>Feel free to modify the text to make it uniquely yours!</p>
<h3 id="heading-wrapping-up">Wrapping Up</h3>
<p>And there you have it – you’ve just launched an EC2 instance and set up a simple web server using HTTPD! With these steps, you’ve not only spun up a server in the cloud but also configured it to be accessible to the world. By following along, you’ve learned the essentials of creating instances, setting up security groups, connecting via SSH, and installing Apache to serve up web content.</p>
<p>Keep exploring EC2’s features, and don’t hesitate to test new configurations and ideas. Each step adds to your cloud skills, bringing you one step closer to mastering AWS. So keep building, experimenting, and, most importantly, enjoying the journey. Happy cloud computing!</p>
<p>You can follow me on</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Connect to Your EC2 Instance Using MobaXterm with SSH and a Keypair (.pem) File ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I’ll walk you through the steps of connecting to your EC2 instance using MobaXterm with a .pem keypair file. Whether you're a beginner dipping your toes into the cloud or an experienced user looking for a quicker method, I’ve got you... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/connect-to-your-ec2-instance-using-mobaxterm/</link>
                <guid isPermaLink="false">6717846983737f44dd20e110</guid>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ec2 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Tue, 22 Oct 2024 10:54:33 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729574902773/f80eb07d-524a-4fa2-a8d8-29c6438d37aa.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I’ll walk you through the steps of connecting to your EC2 instance using MobaXterm with a <code>.pem</code> keypair file. Whether you're a beginner dipping your toes into the cloud or an experienced user looking for a quicker method, I’ve got you covered. So, let’s dive in!</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-mobaxterm">Why MobaXterm?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-1-install-mobaxterm">Step 1: Install MobaXterm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-2-get-your-ec2-instance-public-ip-and-key-pair">Step 2: Get Your EC2 Instance Public IP and Key Pair</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-3-open-mobaxterm-and-start-a-new-ssh-session">Step 3: Open MobaXterm and Start a New SSH Session</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-4-enter-ssh-session-details">Step 4: Enter SSH Session Details</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-5-attach-your-pem-key-pair">Step 5: Attach Your .pem Key Pair</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-6-connect-to-your-ec2-instance">Step 6: Connect to Your EC2 Instance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-step-7-troubleshooting-common-issues">Step 7: Troubleshooting Common Issues</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-why-mobaxterm">Why MobaXterm?</h2>
<p>You may be wondering why we’re using MobaXterm over other SSH tools. Well, for starters, it’s super beginner-friendly, and it combines a bunch of powerful tools in one. You can use it to transfer files, run scripts, or even open multiple sessions simultaneously.</p>
<p>Plus, it’s like the Swiss Army knife for remote connections. Whether you’re working with AWS, Google Cloud, or even a Raspberry Pi at home, MobaXterm can do it all.</p>
<h2 id="heading-step-1-install-mobaxterm">Step 1: Install MobaXterm</h2>
<p>If you’re not already familiar with MobaXterm, it’s basically used for all things remote access. You can download it <a target="_blank" href="https://mobaxterm.mobatek.net/download-home-edition.html">here</a> for free. Installation is super easy – just download, click, and install.</p>
<p>Once you have it set up, fire up MobaXterm and get ready for the fun part.</p>
<h2 id="heading-step-2-get-your-ec2-instance-public-ip-and-key-pair">Step 2: Get Your EC2 Instance Public IP and Key Pair</h2>
<p>Before we continue, there are two key pieces of information you’ll need:</p>
<p><strong>Public IP Address</strong>: This is the unique address AWS assigns to your EC2 instance. To find it, go to the <strong>EC2 Dashboard</strong> in AWS, select your running instance, and grab the <strong>Public IPv4 Address</strong> (it looks like <code>13.123.45.67</code>).</p>
<p><strong>Your .pem File</strong>: This is the private key file you downloaded when you created your EC2 instance. If you didn’t save it, you may have to create a new key pair because AWS only lets you download it once. (No pressure – just don’t lose it this time!)</p>
<h2 id="heading-step-3-open-mobaxterm-and-start-a-new-ssh-session">Step 3: Open MobaXterm and Start a New SSH Session</h2>
<p>Time to work some magic with MobaXterm! Open the app, and you’ll see an intuitive interface. Don’t let all the buttons scare you, just focus on the top left where it says <strong>Session</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729567478544/cf69a56b-9d1e-4de3-b6d8-224634b55ae3.png" alt="MobaXterm user interface" class="image--center mx-auto" width="804" height="307" loading="lazy"></p>
<p>Here’s what to do next:</p>
<ul>
<li><p>Click <strong>Session</strong> (you’ll feel powerful just pressing that button).</p>
</li>
<li><p>In the new window, select <strong>SSH</strong> as the session type.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729567593446/ee8f369d-24be-419d-971f-30e3e4355dd6.png" alt="MobaXterm Session setting tab" class="image--center mx-auto" width="1007" height="672" loading="lazy"></p>
<h2 id="heading-step-4-enter-ssh-session-details">Step 4: Enter SSH Session Details</h2>
<p>It’s time to fill in the details that’ll connect MobaXterm to your EC2 instance. Here’s what you need to know:</p>
<ul>
<li><p><strong>Remote Host</strong>: Enter the <strong>Public IP Address</strong> of your EC2 instance here. Remember, you grabbed that from the EC2 Dashboard earlier.</p>
</li>
<li><p><strong>Username</strong>: If you’re using Amazon Linux, your default username is <code>ec2-user</code>. If you’re on Ubuntu, it’s <code>ubuntu</code>.</p>
</li>
</ul>
<h2 id="heading-step-5-attach-your-pem-key-pair">Step 5: Attach Your .pem Key Pair</h2>
<p>MobaXterm makes it super easy to use your <code>.pem</code> key file for authentication (no converting to <code>.ppk</code> necessary, like you’d have to with other tools).</p>
<p>Here’s how to attach your <code>.pem</code> file:</p>
<ul>
<li><p>Head over to the <strong>Advanced SSH Settings</strong> tab.</p>
</li>
<li><p>Check the <strong>Use private key</strong> option.</p>
</li>
<li><p>Click <strong>Browse</strong> and find your <code>.pem</code> file on your computer.</p>
</li>
<li><p>Select the file and hit <strong>OK</strong>.</p>
</li>
</ul>
<p>It’s like giving MobaXterm the secret key to unlock your EC2 instance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729567798203/535c226e-fbd2-43fc-b1af-a48ce171b974.png" alt="535c226e-fbd2-43fc-b1af-a48ce171b974" class="image--center mx-auto" width="998" height="675" loading="lazy"></p>
<h2 id="heading-step-6-connect-to-your-ec2-instance">Step 6: Connect to Your EC2 Instance</h2>
<p>Now that you’ve filled in all the details, click <strong>OK</strong> to start your session. If everything’s been set up correctly, you should see a terminal pop up, and MobaXterm will work its magic to connect you to your EC2 instance.</p>
<p>🎉 And just like that, you’re in! You should see a terminal window connected to your instance, and now you can start typing commands like a pro.</p>
<h2 id="heading-step-7-troubleshooting-common-issues">Step 7: Troubleshooting Common Issues</h2>
<p>We all know that tech doesn’t always behave. Here are some common problems you might run into—and how to solve them:</p>
<ul>
<li><p><strong>Connection Timed Out</strong>: This could be due to your instance’s security group settings. Make sure your EC2 security group allows inbound traffic on <strong>port 22</strong> (the SSH port) from your IP address.</p>
</li>
<li><p><strong>Authentication Failed</strong>: Ensure you’re using the correct username (<code>ec2-user</code> for Amazon Linux, <code>ubuntu</code> for Ubuntu).</p>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And there you have it! Connecting to your EC2 instance using MobaXterm with your <code>.pem</code> keypair is as simple as following these steps. It’s not rocket science—but it kind of feels like it, doesn’t it? Now that you’ve got your EC2 instance up and running, the sky’s the limit.</p>
<p>So, go on, take what you've learned here, explore, experiment, and, most importantly, have fun with it! Until next time, happy cloud computing! ☁️</p>
<p>You can follow me on</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Cloud Computing? Beginner's Guide to Cloud Computing with AWS ]]>
                </title>
                <description>
                    <![CDATA[ Ever wondered what people mean when they say, “It’s stored in the cloud”? If you’re imagining fluffy white clouds up in the sky storing your pictures, documents, or your Netflix favorites, then you’re in for a surprise! Spoiler alert: the cloud is mu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/beginners-guide-to-cloud-computing-with-aws/</link>
                <guid isPermaLink="false">6712601db2117f64c9ba5c68</guid>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cloud Computing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 18 Oct 2024 13:18:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729159103929/5b4c74fe-3bf5-4ac5-9739-4313d46a8dd1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ever wondered what people mean when they say, “It’s stored in the cloud”? If you’re imagining fluffy white clouds up in the sky storing your pictures, documents, or your Netflix favorites, then you’re in for a surprise!</p>
<p>Spoiler alert: the cloud is much more than that, and it’s a crucial part of what powers our digital world today. So grab a coffee (or tea), get comfy, and let’s dive into the cloudy realm of cloud computing together.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-table-of-contents">Table of Contents</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-so-what-exactly-is-the-cloud">So, What Exactly is the Cloud?</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-a-fun-metaphor">A Fun Metaphor</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-clouds">Types of Clouds</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cloud-service-models-iaas-paas-saas">Cloud Service Models (IAAS, PAAS, SAAS)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-aws">What is AWS?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-do-people-love-aws">Why Do People Love AWS?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-aws-cloud-architecture">AWS Cloud Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-components-of-aws-cloud-architecture">Key Components of AWS Cloud Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-shared-responsibility-model">Shared Responsibility Model</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-aws-regions-availability-zones-edge-locations-amp-local-zones">AWS Regions, Availability Zones, Edge Locations &amp; Local Zones</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-latency">Latency</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ways-to-access-aws-services">Ways to Access AWS Services</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-aws-calculator">AWS Calculator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-up">Wrap Up</a></p>
</li>
</ul>
<h2 id="heading-so-what-exactly-is-the-cloud">So, What Exactly is the Cloud?</h2>
<p>Simply put, the cloud is a network of remote servers around the world that store data, run applications, and power services, so you don’t have to. Think of it as renting a storage unit, except it’s online, more flexible, and can do a lot more than just store things.</p>
<p>Cloud computing is all about accessing these resources over the internet (instead of a physical computer or server that you have to maintain yourself).</p>
<p>For instance, when you upload a photo to Instagram or stream a show on Netflix, you’re accessing files that are stored in the cloud<em>.</em> Instagram and Netflix don’t store all of that data on your phone or laptop – they rely on massive, secure cloud servers to hold it all. Convenient, right?</p>
<h3 id="heading-a-fun-metaphor">A Fun Metaphor</h3>
<p>Imagine that you’re opening a bakery. You’d need a physical location, ovens, ingredients and employees. That’s a huge investment! Now, let’s say there’s a bakery service that provides all of these essentials without you having to own any of them. You just “pay as you bake.” That’s the cloud in a nutshell.</p>
<p>Instead of investing in and maintaining a fleet of servers (which, by the way, take up tons of space, energy, and attention), you rent what you need, use it, and leave the maintenance to the cloud provider. This approach means you can “scale” (make or serve more) without additional investments, making your life much easier and your work far more flexible.</p>
<h2 id="heading-types-of-clouds">Types of Clouds</h2>
<p>Let’s take it a step further with three types of cloud setups. Knowing these will help you understand the different flavors of cloud services:</p>
<ol>
<li><p><strong>Public Cloud</strong>: Imagine renting shared spaces in a massive online “building,” like AWS (Amazon Web Services), Microsoft Azure, or Google Cloud. Here, anyone can rent space or resources, and it’s great for flexibility and cost efficiency.</p>
</li>
<li><p><strong>Private Cloud</strong>: Picture your own bakery setup where only your team has access. Companies set up private clouds for maximum control and privacy. Think of banks or government agencies, they often use private clouds for security reasons.</p>
</li>
<li><p><strong>Hybrid Cloud</strong>: This one’s a mix! It’s like having a private room in a larger shared building, where you can access resources both privately and publicly, depending on your needs. This flexibility is a favorite for businesses looking for the best of both worlds.</p>
</li>
</ol>
<h2 id="heading-cloud-service-models-iaas-paas-saas">Cloud Service Models (IAAS, PAAS, SAAS)</h2>
<ul>
<li>Cloud service models are the ways in which cloud services are delivered to users, each model offering varying levels of control, flexibility, and management. The three primary cloud service models are <strong>IaaS (Infrastructure as a Service)</strong>, <strong>PaaS (Platform as a Service)</strong>, and <strong>SaaS (Software as a Service)</strong>. Each serves different needs depending on the level of infrastructure, platform, or application services that an organization requires.</li>
</ul>
<h4 id="heading-on-premises">On-Premises</h4>
<ul>
<li><p>Imagine that you’re throwing a pizza party, and you want complete control. You buy the ingredients, make the dough, set up the toppings, and bake the pizza in your oven at home. This is on-premises (or “on-prem” for short). You’re responsible for everything, ingredients, cooking, cleaning, and managing the equipment. It’s the same in the tech world. With on-premises computing, companies manage and maintain their own servers, networks, and storage systems, usually in their own data centers.</p>
</li>
<li><p>This traditional approach gives companies total control but also comes with the responsibility of managing everything: hardware maintenance, software updates, data backups, and security. For some companies, this is worth it for the peace of mind of keeping everything in-house. But for others, all this control can be exhausting and expensive.</p>
</li>
</ul>
<h4 id="heading-infrastructure-as-a-service-iaas">Infrastructure as a Service (IaaS)</h4>
<ul>
<li><p>If on-premises is a pizza from scratch, IaaS (Infrastructure as a Service) is like renting a pizza kitchen that’s already equipped with ovens, counters, and tools. All you have to do is bring your ingredients and start cooking. In cloud terms, this means a provider like AWS rents out virtual machines, storage, and networks so you can install them on your operating systems, databases, and applications.</p>
</li>
<li><p><strong>How It Works</strong>: In an IaaS model, AWS or another provider offers the computing power, storage, and networking resources you need, but you’re still in control of what software and applications run on them. This gives you flexibility without the hassle of managing physical hardware.</p>
</li>
<li><p><strong>Why Choose IaaS?</strong></p>
<ul>
<li><p><strong>Scalability</strong>: You can increase or decrease resources based on your needs, like adding more “ovens” when demand is high.</p>
</li>
<li><p><strong>Cost Savings</strong>: You avoid the expense of purchasing and maintaining hardware.</p>
</li>
<li><p><strong>Flexibility</strong>: You get the foundation, but you still control what you build on top, giving you lots of freedom to customize.</p>
</li>
</ul>
</li>
</ul>
<h4 id="heading-platform-as-a-service-paas">Platform as a Service (PaaS)</h4>
<ul>
<li><p>Let’s say you want to get closer to pizza bliss without worrying about managing the kitchen. With PaaS (Platform as a Service), you’re given a ready-made cooking station—fully stocked with dough, sauce, and toppings. You only have to choose your toppings and make the pizza your way.</p>
</li>
<li><p>In tech terms, a PaaS provider manages the underlying infrastructure, including the operating system, servers, storage, and networks. All you need to do is focus on your application code and let the provider handle the rest. AWS Elastic Beanstalk, for example, allows you to deploy and manage applications without getting bogged down in server configurations.</p>
</li>
<li><p><strong>Why Choose PaaS?</strong></p>
<ul>
<li><p><strong>Speed</strong>: You skip the setup and go straight to the cooking part, perfect for developers focusing on building and deploying applications.</p>
</li>
<li><p><strong>Managed Environment</strong>: The provider handles the OS, updates, security patches, and scaling, so you don’t have to worry.</p>
</li>
<li><p><strong>Focus on Code</strong>: It’s ideal if you want to focus on creating your app, not managing infrastructure.</p>
</li>
</ul>
</li>
</ul>
<h4 id="heading-software-as-a-service-saas">Software as a Service (SaaS)</h4>
<ul>
<li><p>Now, if you’re in the mood for ultimate convenience, why not just order pizza delivery? With SaaS (Software as a Service), you don’t have to worry about the kitchen, the ingredients, or even baking. Instead, your pizza arrives hot and ready to eat.</p>
</li>
<li><p>In cloud terms, SaaS is a fully managed software application hosted by the provider and accessible via the internet. Examples include applications like Gmail, Dropbox, or Microsoft 365. You simply log in and start using the service—no installation, updates, or maintenance needed.</p>
</li>
<li><p><strong>Why Choose SaaS?</strong></p>
<ul>
<li><p><strong>Convenience</strong>: Like pizza delivery, it’s ready for immediate consumption, saving you setup and maintenance time.</p>
</li>
<li><p><strong>Accessibility</strong>: Since it’s internet-based, you can access it from anywhere.</p>
</li>
<li><p><strong>Automatic Updates</strong>: The provider handles updates, so you always have the latest features.</p>
</li>
</ul>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729157009842/088adbfa-1766-4c57-8150-b6856316ba62.jpeg" alt="Cloud Service Models" class="image--center mx-auto" width="1280" height="719" loading="lazy"></p>
<h2 id="heading-what-is-aws">What is AWS?</h2>
<ul>
<li>Amazon Web Services, or AWS, is a cloud platform by Amazon that provides a wide range of computing resources, from storage to databases, virtual machines, and AI services. Imagine being able to rent a massive virtual data center without actually needing to buy, set up, or maintain any physical hardware. Sounds great, right? That’s the beauty of AWS. You can launch resources in minutes and pay only for what you use, making it incredibly cost-effective.</li>
</ul>
<h3 id="heading-why-do-people-love-aws">Why Do People Love AWS?</h3>
<ul>
<li>AWS offers a variety of services, making it an all-you-can-eat buffet of tech tools. If you’re building a new app, running a website, or storing data, AWS can handle it all. Plus, it’s reliable, secure, and scalable, which means that you can start small and grow big without having to make drastic changes.</li>
</ul>
<h3 id="heading-aws-cloud-architecture">AWS Cloud Architecture</h3>
<ul>
<li><p>Think of AWS Cloud Architecture as the framework or “blueprint” that defines how an application is built and how it interacts with different services on the AWS platform. Just like a city’s infrastructure needs roads, buildings, utilities, and a way to manage traffic, an AWS cloud architecture consists of various components that keep everything running smoothly. These components include networking, compute power, storage, databases, and security services.</p>
</li>
<li><p>At its core, AWS Cloud Architecture is designed to help businesses create reliable, scalable, and secure applications without having to build everything from scratch. AWS offers a wide array of tools and services that fit together like puzzle pieces, making it easy to create a customized, efficient cloud environment.</p>
</li>
</ul>
<h3 id="heading-key-components-of-aws-cloud-architecture">Key Components of AWS Cloud Architecture</h3>
<ul>
<li>To really understand AWS Cloud Architecture, let’s look at some of its essential components. Each piece has a specific role, and together, they make up a solid, high-functioning cloud environment.</li>
</ul>
<h5 id="heading-1-compute">1. <strong>Compute</strong></h5>
<p>Every cloud-based application needs processing power to run its code, handle user requests, and process data. This is where <strong>compute services</strong> come in.</p>
<ul>
<li><p><strong>Amazon EC2 (Elastic Compute Cloud)</strong>: Think of EC2 as the powerhouse behind your app. EC2 instances are virtual servers that can be customized to fit your app’s needs—just like choosing between a laptop, a desktop, or a supercomputer based on your work requirements.</p>
</li>
<li><p><strong>AWS Lambda</strong>: AWS Lambda is the star of serverless computing, letting you run code without managing any servers. It’s perfect for small tasks that don’t require constant resources. For example, if you want to automatically resize photos every time they’re uploaded, Lambda can handle that with ease!</p>
</li>
</ul>
<h5 id="heading-2-storage">2. <strong>Storage</strong></h5>
<p>All apps need a place to store their data—think files, user profiles, or transaction records. AWS provides several storage options to meet a wide range of needs.</p>
<ul>
<li><p><strong>Amazon S3 (Simple Storage Service)</strong>: S3 is like an expandable cloud-based filing cabinet where you can store and retrieve virtually unlimited amounts of data. It’s highly secure and accessible, making it a popular choice for data storage.</p>
</li>
<li><p><strong>Amazon EBS (Elastic Block Store)</strong>: EBS works like a hard drive attached to an EC2 instance, making it ideal for applications that need high-performance storage.</p>
</li>
</ul>
<h5 id="heading-3-databases">3. <strong>Databases</strong></h5>
<p>For many applications, data needs to be stored in a structured way, so AWS provides several database options to suit different data types.</p>
<ul>
<li><p><strong>Amazon RDS (Relational Database Service)</strong>: RDS handles structured data like customer records or order information. You can set up databases like MySQL or PostgreSQL, and AWS takes care of maintenance and backups.</p>
</li>
<li><p><strong>Amazon DynamoDB</strong>: For high-traffic applications that need quick access to data, DynamoDB offers fast, flexible NoSQL storage that scales automatically.</p>
</li>
</ul>
<h5 id="heading-4-networking">4. <strong>Networking</strong></h5>
<p>To keep everything connected and ensure data flows securely, AWS offers networking services that act as the “highways” of your cloud architecture.</p>
<ul>
<li><p><strong>Amazon VPC (Virtual Private Cloud)</strong>: VPC creates a secure virtual network where you can control who accesses your resources. It’s like having your own private space in AWS’s giant data center.</p>
</li>
<li><p><strong>AWS CloudFront</strong>: CloudFront is a Content Delivery Network (CDN) that speeds up content delivery by caching it closer to users. So, if your app has users all around the world, CloudFront ensures they get the best experience possible by reducing loading times.</p>
</li>
</ul>
<h5 id="heading-5-security-and-identity">5. <strong>Security and Identity</strong></h5>
<p>AWS takes security seriously, and with tools like <strong>AWS Identity and Access Management (IAM)</strong> and <strong>AWS Shield</strong>, you can manage access to resources and protect your architecture from security threats.</p>
<ul>
<li><p><strong>IAM (Identity and Access Management)</strong>: IAM allows you to create and manage permissions for each user and service, so you can control who can do what. This ensures your data stays safe and only the right people have access.</p>
</li>
<li><p><strong>AWS Shield</strong>: For those worried about DDoS attacks, Shield provides protection by automatically filtering harmful traffic.</p>
</li>
</ul>
<h5 id="heading-putting-it-all-together-how-aws-cloud-architecture-works"><strong>Putting It All Together: How AWS Cloud Architecture Works</strong></h5>
<p>So, how do all these pieces work together? Imagine building an online store on AWS:</p>
<ol>
<li><p><strong>Compute (EC2/Lambda)</strong>: Your store’s backend runs on EC2 instances, handling requests and processing orders. A Lambda function might handle smaller tasks, like sending confirmation emails.</p>
</li>
<li><p><strong>Storage (S3)</strong>: Product photos and user-uploaded files are stored in S3, keeping them secure and accessible.</p>
</li>
<li><p><strong>Database (RDS)</strong>: Customer details, order information, and product listings are stored in an RDS database, so you can easily track orders and manage inventory.</p>
</li>
<li><p><strong>Networking (VPC &amp; CloudFront)</strong>: VPC keeps your network secure, and CloudFront speeds up the delivery of your site to customers around the globe.</p>
</li>
<li><p><strong>Security (IAM &amp; Shield)</strong>: IAM controls user access, ensuring only authorized staff can access sensitive data. Shield guards against DDoS attacks, keeping your site up and running even in high-traffic situations.</p>
</li>
</ol>
<h3 id="heading-shared-responsibility-model">Shared Responsibility Model</h3>
<ul>
<li><p>Imagine renting a house, and AWS owns the house and makes sure that the structure is safe and secure. The roof is solid, the doors lock, and the plumbing works. But when it comes to what happens <em>inside</em>—the furniture, who has keys, and how you keep it clean—that’s your job as the tenant.</p>
</li>
<li><p>In cloud terms, AWS takes care of the infrastructure, making sure the servers are protected and that their data centers are secure. But the data you put on AWS, the applications you run, and the security settings you choose are your responsibility. It’s a team effort where AWS keeps the cloud safe, and you keep what’s in it secure.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729157534482/562b3616-5339-4ec8-8ca3-540fdc48d9a4.png" alt="AWS Shared Responsibility" class="image--center mx-auto" width="977" height="468" loading="lazy"></p>
<h4 id="heading-breaking-down-the-shared-responsibility-model">Breaking Down the Shared Responsibility Model</h4>
<p>The Shared Responsibility Model is divided into two main parts: <strong>Security of the Cloud</strong> (that’s AWS’s job) and <strong>Security in the Cloud</strong> (that’s on you).</p>
<h5 id="heading-1-security-of-the-cloud">1. Security <strong>of</strong> the Cloud</h5>
<p>AWS is like the security guard for the entire cloud environment. Here’s what AWS is responsible for:</p>
<ul>
<li><p><strong>Data Center Security</strong>: AWS is in charge of the physical security of its data centers. They have strict access controls, security cameras, and even biometric scanning to make sure only authorized personnel can enter. No need to worry about anyone physically accessing your data!</p>
</li>
<li><p><strong>Hardware and Software Maintenance</strong>: AWS takes care of maintaining, patching, and updating the underlying hardware and software. This includes managing the physical servers, storage devices, and networking equipment that power AWS services.</p>
</li>
<li><p><strong>Network Security</strong>: AWS ensures that the networking infrastructure is protected from threats. They deploy firewalls, DDoS protection, and other measures to keep malicious actors out.</p>
</li>
</ul>
<p>Think of AWS’s responsibility as creating and maintaining a highly secure cloud platform. This means that you can count on AWS to keep the data centers running smoothly, provide reliable servers, and handle infrastructure-level threats.</p>
<h5 id="heading-2-security-in-the-cloud">2. Security in the Cloud</h5>
<p>Now, here’s where you come in. While AWS provides a secure infrastructure, you’re in charge of what you do with it. Your responsibilities include:</p>
<ul>
<li><p><strong>Data Protection</strong>: You decide how your data is encrypted and who can access it. For example, AWS provides options to encrypt your data at rest and in transit, but it’s up to you to turn on encryption and manage your encryption keys.</p>
</li>
<li><p><strong>Identity and Access Management (IAM)</strong>: AWS’s IAM service lets you control who has access to your AWS resources. It’s like having keys to different rooms in a house—some people may only need access to the kitchen, while others need access to every room. By setting roles and permissions, you decide who can do what.</p>
</li>
<li><p><strong>Configuring Security Groups</strong>: Security Groups are like firewalls for your AWS resources, controlling what can enter and leave. You decide what traffic is allowed and where it’s allowed to go. Think of it as creating security rules for your cloud environment.</p>
</li>
<li><p><strong>Application Security</strong>: If you’re running a web application on AWS, you’re responsible for securing the code and protecting against vulnerabilities, like SQL injection or cross-site scripting. AWS can’t know what’s in your code, so they leave application security in your capable hands.</p>
</li>
<li><p><strong>Regular Audits and Compliance</strong>: AWS offers tools to help with auditing, but you’re the one who needs to monitor and ensure compliance with industry standards. Regular audits can help you check that everything is running smoothly and according to your security needs.</p>
</li>
</ul>
<h2 id="heading-aws-regions-availability-zones-edge-locations-amp-local-zones">AWS Regions, Availability Zones, Edge Locations &amp; Local Zones</h2>
<p>If you’ve dipped your toes into AWS, you’ve probably come across words like “Regions,” “Availability Zones,” “Edge Locations,” and “Local Zones.” And let’s be honest, they can sound a bit intimidating at first. But understanding these terms is key to building a successful application on AWS. It’s like getting a map before you venture into a theme park—knowing the layout makes the whole experience smoother and more enjoyable.</p>
<p>So, let’s take a fun tour of the AWS “cloud park” and see how these areas fit together!</p>
<h4 id="heading-1-aws-regions">1. <strong>AWS Regions</strong></h4>
<p>Imagine AWS as a theme park with entrances all over the world. <strong>Regions</strong> are like the different main entrances to this massive park. Each Region is a fully equipped area of AWS infrastructure located in a specific part of the world. There are over 34 Regions globally, each providing a complete set of services and facilities.</p>
<p>Choosing a Region is like choosing which entrance to start your journey. If most of your customers are in Europe, you might pick a Region closer to them, like Frankfurt or London. This helps reduce latency, meaning that users experience faster load times and smoother interactions.</p>
<h4 id="heading-2-availability-zones-azs">2. <strong>Availability Zones (AZs)</strong></h4>
<p>Once you’re inside a Region (entrance), you’ll find <strong>Availability Zones</strong>, or AZs, which are like the different sections of the theme park. Each AZ is a separate, independent data center close to others within the same Region but with its own unique power, cooling, and network sources. This setup provides redundancy, a critical factor for high availability and reliability.</p>
<p>Here’s why this is important: Imagine running an application that needs to be online 24/7. If you host it in just one AZ, and that AZ has a power issue, your app might go down. But by setting up your app across multiple AZs (say, on both “Adventure Land” and “Fantasy Land” floors), if one zone experiences a problem, the others will keep your application up and running, creating a seamless experience for users.</p>
<h4 id="heading-3-edge-locations">3. <strong>Edge Locations</strong></h4>
<p>Next, let’s move on to <strong>Edge Locations</strong>, which are like the pop-up stands you see throughout the park, serving everything from maps to quick snacks. Edge Locations are strategically placed “mini AWS stations” that deliver cached data close to your users, no matter where they are.</p>
<p>AWS’s Content Delivery Network, <strong>Amazon CloudFront</strong>, operates through these Edge Locations. So, if you have a video or website image that people in Japan and South Africa need to access, CloudFront delivers it from the closest Edge Location instead of the central server. This shortens load times and provides a faster, more responsive experience. Edge Locations are perfect for apps with heavy media needs, as they ensure content loads quickly and efficiently.</p>
<h4 id="heading-4-local-zones">4. <strong>Local Zones</strong></h4>
<p>Finally, we have <strong>Local Zones</strong>. These are like the VIP zones within the park, giving visitors near-instant access to certain attractions. Local Zones are smaller clusters of AWS infrastructure, set up closer to specific cities to provide ultra-low latency for applications that need rapid response times.</p>
<p>Let’s say you’re running a gaming app, and you want players in Los Angeles to experience minimal lag. Using a Local Zone in Los Angeles gives those users immediate access to your application, keeping the experience fast and smooth. Local Zones are ideal for services that require high-speed processing in metropolitan areas like online gaming, media production, and virtual reality.</p>
<h4 id="heading-putting-it-all-together-planning-your-aws-adventure">Putting It All Together: Planning Your AWS Adventure</h4>
<p>To design your application architecture, think about where your users are and what kind of experience you want them to have. Here’s a quick guide to help you plan:</p>
<ul>
<li><p><strong>Regions</strong>: Pick a Region close to your primary user base to minimize latency. This helps provide a faster, more responsive experience for users.</p>
</li>
<li><p><strong>Availability Zones (AZs)</strong>: Use multiple AZs within a Region to build a resilient, high-availability application. This way, if one zone goes down, others will keep your app running.</p>
</li>
<li><p><strong>Edge Locations</strong>: For content-heavy applications, like streaming services or e-commerce sites, use CloudFront’s Edge Locations to cache and deliver content quickly, no matter where users are.</p>
</li>
<li><p><strong>Local Zones</strong>: For applications needing ultra-low latency in specific cities, Local Zones bring AWS infrastructure closer to users, creating a near-instant experience for high-demand applications.</p>
</li>
</ul>
<p>You can find latest numbers about regions, AZs, edge locations and local zones <a target="_blank" href="https://aws.amazon.com/about-aws/global-infrastructure/?p=ngi&amp;loc=1">here</a></p>
<h3 id="heading-latency">Latency</h3>
<ul>
<li><p>In simplest terms, latency is the delay between a user’s action and a web application’s response to that action. Imagine it like a digital echo—say something, and there’s a tiny pause before you hear it back. Latency is measured in milliseconds (ms), and the lower the latency, the faster your connection feels.</p>
</li>
<li><p><strong>Example:</strong> Let’s say you’re browsing a website from your home in New York, but the server hosting the website is located in Sydney. Your request has to travel all the way to Sydney, and the server’s response has to travel all the way back to you. Even though data travels fast (really fast!), the distance still creates a delay. And that delay? That’s latency.</p>
</li>
</ul>
<h4 id="heading-why-does-latency-matter">Why Does Latency Matter?</h4>
<ul>
<li><p>A little bit of latency might not seem like a big deal, but when it adds up, it can make for a frustrating user experience. Have you ever tried to play a multiplayer video game only to get that dreaded “lag” just as you’re about to win? Or maybe you’ve waited an extra couple of seconds for a video to load? High latency is often the culprit here.</p>
</li>
<li><p><strong>Low Latency = Fast, Responsive Experience</strong></p>
</li>
<li><p><strong>High Latency = Delays and Frustration</strong></p>
</li>
<li><p>When latency is high, every interaction with an app feels delayed, which can drive users away. This is why companies like AWS invest in minimizing latency by building infrastructure close to users worldwide.</p>
</li>
</ul>
<h4 id="heading-aws-and-latency-how-does-aws-minimize-latency">AWS and Latency: How Does AWS Minimize Latency?</h4>
<ul>
<li>AWS takes latency seriously, and its infrastructure is designed to keep latency as low as possible for users worldwide. Here’s how AWS tackles latency head-on:</li>
</ul>
<ul>
<li><p><strong>Regions and Availability Zones (AZs)</strong>: AWS has data centers called Regions and AZs spread across the globe. By choosing a Region close to your primary user base, you can reduce latency by minimizing the distance data has to travel.</p>
</li>
<li><p><strong>Edge Locations and Amazon CloudFront</strong>: AWS has Edge Locations worldwide that work with Amazon CloudFront, its Content Delivery Network (CDN). Think of Edge Locations as data hotspots in popular areas—by caching content in these locations, AWS makes sure users get the fastest load times possible, no matter where they’re located.</p>
</li>
<li><p><strong>Local Zones</strong>: For applications that need ultra-low latency in specific cities, AWS Local Zones bring infrastructure closer to metropolitan areas, providing lightning-fast access for applications that can’t afford any lag.</p>
</li>
</ul>
<h4 id="heading-a-latency-analogy-ordering-pizza">A Latency Analogy: Ordering Pizza</h4>
<ul>
<li>Let’s break it down with a pizza analogy. Imagine ordering a pizza from a restaurant:</li>
</ul>
<ul>
<li><p><strong>Low Latency</strong>: The pizza place is just a few blocks away, so you get your pizza piping hot in no time.</p>
</li>
<li><p><strong>High Latency</strong>: Now imagine the pizza place is on the other side of town. Your pizza arrives late and lukewarm because of the long journey. That’s high latency!</p>
</li>
</ul>
<p>In AWS terms, having a Region or Edge Location close to users is like ordering pizza from a nearby shop instead of one across town. The shorter the distance, the less time you spend waiting for your “pizza” (or, in this case, your data) to arrive.</p>
<h3 id="heading-ways-to-access-aws-services">Ways to Access AWS Services</h3>
<p>When you’re diving into AWS, you’ll quickly realize that there’s a lot going on behind the scenes. But getting into AWS and accessing its suite of cloud services isn’t complicated—it’s actually quite user-friendly. AWS provides several ways for you to interact with its services, whether you prefer clicking buttons, typing commands, or even writing code. It’s like a big virtual house with multiple front doors—choose the one that suits you best!</p>
<h4 id="heading-1-aws-management-console-the-point-and-click-option">1. <strong>AWS Management Console: The Point-and-Click Option</strong></h4>
<p>If you’re a visual person, the AWS Management Console is going to feel like home. The console is a web-based interface that lets you manage your AWS resources through a series of friendly, clickable dashboards. Imagine it as the AWS “control room,” where you can launch and manage services with just a few clicks.</p>
<p>The AWS Console is ideal for beginners and those who want a clear, intuitive way to explore services. It’s also perfect for anyone setting up infrastructure without needing deep technical knowledge—no command-line skills required!</p>
<p><strong>What you can do with the AWS Console</strong>:</p>
<ul>
<li><p>Launch and manage EC2 instances (virtual servers)</p>
</li>
<li><p>Set up S3 storage buckets</p>
</li>
<li><p>Configure IAM (Identity and Access Management) roles for security</p>
</li>
<li><p>Access billing and cost management tools to keep an eye on your budget</p>
</li>
</ul>
<p><strong>Best for:</strong> Visual learners, beginners, and anyone who prefers a simple, no-code approach to managing AWS.</p>
<h4 id="heading-2-aws-command-line-interface-cli-for-the-command-lovers">2. <strong>AWS Command Line Interface (CLI): For the Command Lovers</strong></h4>
<p>If you’re comfortable with typing commands, the AWS CLI is your best friend. The AWS CLI is a command-line tool that lets you manage AWS services through typed commands in your terminal or command prompt. It’s a powerful option for those who prefer speed and efficiency or want to automate tasks without relying on a graphical interface.</p>
<p>With the CLI, you can script entire workflows, automate processes, and manage resources from any device with a terminal. Plus, it’s often faster to type a single command than to click through multiple pages in the console!</p>
<p><strong>Example command</strong>:</p>
<pre><code class="lang-bash">aws ec2 describe-instances
</code></pre>
<p>This command lists all your running EC2 instances. With a few lines of code, you can check your resources, scale services up or down, and even handle complex configurations without ever opening a browser.</p>
<p><strong>Best for:</strong> Power users, developers, sysadmins, and anyone who loves efficiency and automation.</p>
<h4 id="heading-3-aws-sdks-for-the-coders-and-developers">3. <strong>AWS SDKs: For the Coders and Developers</strong></h4>
<p>If you’re a developer who wants to integrate AWS services directly into your code, AWS SDKs (Software Development Kits) are here to help. AWS provides SDKs for multiple programming languages, like Python, JavaScript, Java, and Ruby, allowing you to interact with AWS from within your applications.</p>
<p>The SDKs are like AWS “plug-ins” that you add to your code, allowing you to access services, automate processes, and build applications that directly communicate with AWS resources. For example, with the AWS SDK for Python (Boto3), you can write code to upload files to S3, run queries on DynamoDB, or trigger Lambda functions.</p>
<p><strong>Example with Boto3 in Python</strong>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3

s3 = boto3.client(<span class="hljs-string">'s3'</span>)
s3.upload_file(<span class="hljs-string">'file.txt'</span>, <span class="hljs-string">'mybucket'</span>, <span class="hljs-string">'file.txt'</span>)
</code></pre>
<p>In just a few lines, this code uploads a file to an S3 bucket. Pretty cool, right?</p>
<p><strong>Best for:</strong> Developers who want to integrate AWS functionality directly into their applications.</p>
<h4 id="heading-4-aws-cloudformation-the-blueprint-builder"><strong>4. AWS CloudFormation: The Blueprint Builder</strong></h4>
<p>If you’re interested in automating infrastructure setup and configuration, AWS CloudFormation is your go-to tool. CloudFormation allows you to create a “blueprint” (a JSON or YAML file) that defines the AWS resources and configurations you want. AWS then uses this blueprint to set everything up for you, saving you the time and effort of doing it manually.</p>
<p>With CloudFormation, you can create and manage “stacks” of resources—think EC2 instances, S3 buckets, databases, and more—by writing a single template. This setup is ideal for deploying applications in a consistent and repeatable way.</p>
<p><strong>Example CloudFormation snippet</strong>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Resources:</span>
  <span class="hljs-attr">MyBucket:</span>
    <span class="hljs-attr">Type:</span> <span class="hljs-string">'AWS::S3::Bucket'</span>
    <span class="hljs-attr">Properties:</span>
      <span class="hljs-attr">BucketName:</span> <span class="hljs-string">'my-example-bucket'</span>
</code></pre>
<p>This simple code creates an S3 bucket named “my-example-bucket.” Once you’ve set up a template, you can deploy it again and again, making it easy to replicate infrastructure across different environments.</p>
<p><strong>Best for:</strong> DevOps engineers, architects, and teams who need an automated, repeatable infrastructure setup.</p>
<h4 id="heading-5-aws-apis-direct-access-for-ultimate-flexibility"><strong>5. AWS APIs: Direct Access for Ultimate Flexibility</strong></h4>
<p>If you’re looking for full control and direct access to AWS services, AWS APIs are the way to go. AWS provides APIs for almost every service, which means that you can interact with AWS directly by making HTTP requests, without needing to rely on the AWS Console, CLI, or SDKs.</p>
<p>APIs allow developers to call AWS services programmatically—sending requests, retrieving responses, and performing operations from within any environment that can make HTTP requests. They’re perfect for building customized solutions, automating workflows, and integrating AWS services into existing systems or third-party applications.</p>
<p><strong>Example AWS API Call</strong>: Using an HTTP request, you can retrieve information about an S3 bucket or initiate a Lambda function. Here’s a quick example of what an API request might look like to list objects in an S3 bucket:</p>
<pre><code class="lang-plaintext">GET /mybucket?list-type=2 HTTP/1.1
Host: s3.amazonaws.com
Authorization: AWS4-HMAC-SHA256 ...
</code></pre>
<p>With the right permissions and authentication, this API call allows you to fetch data about the objects in an S3 bucket directly.</p>
<h4 id="heading-benefits-of-using-aws-apis">Benefits of Using AWS APIs</h4>
<ul>
<li><p><strong>Direct Integration</strong>: APIs allow you to access AWS services from any system, language, or platform that supports HTTP requests.</p>
</li>
<li><p><strong>Lightweight and Flexible</strong>: Since APIs don’t require SDKs or extra tools, they’re an efficient, minimalistic option.</p>
</li>
<li><p><strong>Ideal for Automation</strong>: APIs are great for creating custom workflows and automating interactions with AWS services, especially for DevOps teams or developers managing complex systems.</p>
</li>
</ul>
<p><strong>Best for:</strong> Advanced developers, system integrators, and teams needing custom or platform-independent ways to interact with AWS.</p>
<h4 id="heading-comparison-table">Comparison Table</h4>
<p>Here’s an updated table including AWS APIs for easier reference:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Access Method</strong></td><td><strong>Best For</strong></td><td><strong>Skill Level</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>AWS Console</strong></td><td>Visual learners, beginners</td><td>Beginner to intermediate</td></tr>
<tr>
<td><strong>AWS CLI</strong></td><td>Power users, sysadmins, automation enthusiasts</td><td>Intermediate to advanced</td></tr>
<tr>
<td><strong>AWS SDKs</strong></td><td>Developers integrating AWS in code</td><td>Intermediate to advanced</td></tr>
<tr>
<td><strong>AWS CloudFormation</strong></td><td>DevOps, automated deployments</td><td>Advanced</td></tr>
<tr>
<td><strong>AWS APIs</strong></td><td>Custom integrations, lightweight automation</td><td>Advanced</td></tr>
</tbody>
</table>
</div><h2 id="heading-aws-calculator">AWS Calculator</h2>
<p>The AWS Pricing <a target="_blank" href="https://calculator.aws/#/addService">Calculator</a> isn’t just a budgeting tool, it’s your cloud co-pilot, helping you explore the potential of AWS without the financial surprises. Whether you’re experimenting with a single EC2 instance or planning a multi-service, enterprise-scale setup, this calculator can break down costs, project your savings, and give you peace of mind with a well-rounded view of your expenses.</p>
<p>So, next time you're thinking, "What will this cloud project really cost?", take the AWS Calculator for a spin. You might just discover a way to achieve big things in the cloud without stretching your budget!</p>
<h2 id="heading-wrap-up">Wrap Up</h2>
<p>And there you have it, a tour through the world of AWS and what it can mean for you or your projects. Whether you’re just dipping your toes into cloud waters or strategizing a multi-cloud empire, AWS offers tools and flexibility to support your journey.</p>
<p>So, go on, take what you've learned here, explore, experiment, and, most importantly, have fun with it! Until next time, happy cloud computing! ☁️</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Master Boot Record Disk Partitioning Works in Linux ]]>
                </title>
                <description>
                    <![CDATA[ Efficient storage management is a crucial aspect of maintaining a well-organized computing environment. In this detailed guide, we'll explore the features of Master Boot Record (MBR) disk partitioning using the parted command on Linux. Additionally, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-mbr-works-in-linux/</link>
                <guid isPermaLink="false">66d45f67d14641365a0508f5</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ storage ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Wed, 07 Feb 2024 10:29:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Frame-1000004568-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Efficient storage management is a crucial aspect of maintaining a well-organized computing environment.</p>
<p>In this detailed guide, we'll explore the features of Master Boot Record (MBR) disk partitioning using the <code>parted</code> command on Linux.</p>
<p>Additionally, we'll cover the process of adding a new hard disk in VMware, as well as how to format and mount a newly created partition using <code>mkfs</code> and <code>fstab</code>, respectively.</p>
<h2 id="heading-table-of-contents"><strong>Table Of Contents</strong></h2>
<p>Here's what we'll cover in this comprehensive guide:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-overview-of-mbr">Overview of MBR</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-introduction-to-the-parted-utility">Introduction to Parted Utility</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-identify-disks">How to Identify Disks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-launch-parted">How to Launch Parted</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-new-mbr-partition-table">How to Create a New MBR Partition Table</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-primary-partitions">How to Create Primary Partitions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-display-partition-information">How to Display Partition Information</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-format-the-partition-with-mkfs">How to Format the Partition with mkfs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-automate-mounting-with-fstab">How to Automate Mounting with fstab</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-mount-a-partition">How to Mount a Partition</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-logical-partitions">How to Create Logical Partitions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-overview-of-mbr">Overview of MBR</h2>
<p>MBR is a legacy partitioning scheme used on BIOS-based systems, with a 512-byte sector at the beginning of the storage device which contains partition information and the bootloader.</p>
<p>The 512 bytes of the MBR are organized as follows:</p>
<ul>
<li><p><strong>Master Boot Code (446 bytes):</strong> This section contains the executable code responsible for loading the operating system. It locates the active (bootable) partition and passes control to its boot sector.</p>
</li>
<li><p><strong>Partition Table (64 bytes):</strong> The next 64 bytes are reserved for the partition table, which can describe up to four primary partitions or three primary partitions and one extended partition.</p>
</li>
<li><p><strong>MBR Signature (2 bytes):</strong> The last two bytes contain a signature (0x55AA), indicating that this is a valid MBR.</p>
</li>
</ul>
<h2 id="heading-introduction-to-the-parted-utility">Introduction to the Parted Utility</h2>
<p><code>parted</code> is a command-line utility designed for creating, resizing, and managing disk partitions on Linux systems.</p>
<p>It offers a comprehensive set of features for handling disk-related tasks and is widely used due to its flexibility and robust capabilities. The primary goals of <code>parted</code> include:</p>
<ul>
<li><p><strong>Partition Creation and Resizing:</strong> <code>parted</code> enables users to create new partitions on a disk, resize existing partitions, and adjust the allocation of disk space.</p>
</li>
<li><p><strong>File System Support:</strong> It supports various file systems, including ext2, ext3, ext4, FAT, NTFS, and more, allowing users to choose the file system that best suits their needs.</p>
</li>
<li><p><strong>Partition Table Manipulation:</strong> <code>parted</code> facilitates the management of partition tables, including creating, modifying, and deleting partitions within these tables.</p>
</li>
<li><p><strong>Sector-level Operations:</strong> The utility operates at the sector level, allowing for precise control and manipulation of disk structures.</p>
</li>
</ul>
<h3 id="heading-how-to-install-parted">How to Install Parted</h3>
<p>You can install <code>parted</code> on your system using this command:</p>
<pre><code class="lang-bash">yum install parted
</code></pre>
<p>Before creating partition we need to add new disk to our virtual machine. I am using VMware. Go on and start RHEL virtual machine.</p>
<p>First we need to go to Player option on top left corner and then to the Manage option. Using that option, you can select virtual machine settings.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Add new hard disk in VMware</em></p>
<p>Click on "add to new hard disk". Then select hard disk and keep pressing on next until it asks for disk capacity. For learning purposes, add only 5 GB disk.</p>
<p>Continue clicking next until you get to the finish option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot--3--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Adding virtual hard disk - 1</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot--4--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Adding virtual hard disk - 2</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot--5-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Adding virtual hard disk - 3</em></p>
<p>We are focusing on creating partition, so we'll not focus on parts which are not needed for partition.</p>
<p>Next, restart your virtual machine to reflect the newly added hard disk.</p>
<h3 id="heading-how-to-identify-disks">How to Identify Disks</h3>
<p>Identifying disks is a crucial step in the process of disk partitioning as it ensures that you are working with the correct storage device on your system.</p>
<p>Use the <code>lsblk</code> command to display information about block devices, including hard drives and partitions.</p>
<pre><code class="lang-bash">lsblk
</code></pre>
<p>Look for the disk you want to partition. Disk names are typically in the format <code>/dev/sdX</code>, where 'X' is a lowercase letter representing the disk. For example, <code>/dev/sda</code>, <code>/dev/sdb</code>, etc.</p>
<h3 id="heading-how-to-launch-parted">How to Launch Parted</h3>
<p>Open a terminal and launch <code>parted</code> for the target disk:</p>
<pre><code class="lang-bash">parted /dev/sdX
</code></pre>
<p>This initiates the <code>parted</code> utility with elevated privileges and directs it to focus on the specified storage device (<code>/dev/sdX</code>).</p>
<p>Once executed, the user enters the <code>parted</code> interactive mode for the specified device, enabling the configuration and management of partitions on that particular storage device.</p>
<h3 id="heading-how-to-create-a-new-mbr-partition-table">How to Create a New MBR Partition Table</h3>
<p>If the disk is unpartitioned, create a new MBR partition table using this command:</p>
<pre><code class="lang-bash">(parted) mklabel msdos
</code></pre>
<p>This instructs <code>parted</code> to create a new MBR partition table on the currently selected storage device. This action will remove any existing partition information on the device, effectively starting with a clean slate for partitioning.</p>
<p>It's important to note that this command should be used with caution, as it erases the existing partition table and all associated data on the device.</p>
<h2 id="heading-how-to-create-primary-partitions">How to Create Primary Partitions</h2>
<p>You can create a primary partition with specified filesystem type, start, and end:</p>
<pre><code class="lang-bash">(parted) mkpart primary [filesystem-type] [start] [end]
</code></pre>
<ul>
<li><p><code>mkpart</code>: This is the <code>parted</code> command used to create a new partition. The term "mkpart" stands for "make partition."</p>
</li>
<li><p><code>primary</code>: This specifies the type of partition to be created. In this case, it's a primary partition. Primary partitions are the basic partitions on a disk, and they can be used to install an operating system or store data.</p>
</li>
<li><p><code>[filesystem-type]</code>: Replace this placeholder with the desired filesystem type for the partition. Common filesystem types include <code>ext4</code>, <code>ntfs</code>, <code>fat32</code>, and so on.</p>
</li>
<li><p><code>[start]</code> and <code>[end]</code>: These placeholders represent the starting and ending points of the partition, specified in megabytes (MB) or as a percentage of the total disk size. For example, you might define the partition to start at 1 GB and end at 10 GB.</p>
</li>
</ul>
<h3 id="heading-how-to-display-partition-information">How to Display Partition Information</h3>
<p>Use this command to verify the partition layout:</p>
<pre><code class="lang-bash">(parted) <span class="hljs-built_in">print</span> free
</code></pre>
<p>When you enter <code>(parted) print free</code> in the <code>parted</code> interactive mode, it will provide a summary of the free space available on the selected disk, including details such as the starting and ending points of the unallocated space, its size, and any constraints on creating new partitions within that space.</p>
<p>Here's the output:</p>
<pre><code class="lang-bash">(parted) <span class="hljs-built_in">print</span> free
Model: ABC Storage Device
Disk /dev/sdX: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: msdos
Disk Flags:

Number  Start   End     Size    Type  File system  Flags
        32.3kB  1049kB  1017kB  Free Space
 1      1049kB  256MB   255MB   primary  ext4         boot
 2      256MB   512MB   256MB   primary  linux-swap
 3      512MB   1000GB  1000GB  primary  ntfs
</code></pre>
<p>Press <code>ctrl + d</code> to get out of parted.</p>
<h3 id="heading-how-to-format-the-partition-with-mkfs">How to Format the Partition with <code>mkfs</code></h3>
<p>After partitioning, format the partition with a desired filesystem (for example: ext4)</p>
<pre><code class="lang-bash">mkfs.[filesystem-type] /dev/sdX1
</code></pre>
<p>This tells the system to create a file system of the specified type on the designated partition. After executing this command, the chosen file system will be created on the partition, and it will be ready to store files and data.</p>
<h3 id="heading-how-to-automate-mounting-with-fstab">How to Automate Mounting with <code>fstab</code></h3>
<p>You can find the UUID of the partition using this command:</p>
<pre><code class="lang-bash">sudo blkid /dev/sdX1
</code></pre>
<p>Edit <code>/etc/fstab</code> to include an entry for automatic mounting, and make sure filesystem-type is as same as filesystem type of <code>mkfs.[filesystem-type]</code></p>
<p>The <code>/etc/fstab</code> file, short for "file systems table," is a crucial configuration file on Unix and Unix-like operating systems, including Linux. It is used to define how storage devices (such as hard drives and partitions) should be mounted into the file system.</p>
<p>The primary purpose of the <code>/etc/fstab</code> file is to specify how various storage devices should be mounted during the system's startup process.</p>
<pre><code class="lang-bash">UUID=[your-uuid] /dir-to-mount-path [filesystem-type] defaults 0 0
</code></pre>
<p>Here's an example:</p>
<pre><code class="lang-bash">UUID=127854Vd344HHttRpq977739 /kedar ext4 defaults 0 0
</code></pre>
<p><code>UUID=127854Vd344HHttRpq977739</code>: This part specifies the Universally Unique Identifier (UUID) of the block device or partition to be mounted. The UUID is a unique identifier assigned to the filesystem, ensuring a consistent reference even if the device names change. In this case, the UUID is "127854Vd344HHttRpq977739."</p>
<p><code>/kedar</code>: This part indicates the mount point, which is the directory in the file system where the device specified by the UUID will be attached. In this example, the mount point is "/kedar."</p>
<p><code>ext4</code>: This specifies the type of the file system on the device. In this case, it's "ext4," which is a commonly used file system on Linux.</p>
<p><code>defaults</code>: The "defaults" option is a shorthand for a set of commonly used mount options. It includes options like read/write access and allows executing binaries from the file system. If more specific options are needed, they can be listed explicitly.</p>
<p><code>0</code>: This field represents the dump option. It is used by the <code>dump</code> command to determine whether the file system should be backed up. A value of 0 indicates that no automatic backups are required.</p>
<p><code>0</code>: The last field represents the pass option. It is used by the <code>fsck</code> (file system check) utility to determine the order in which file systems are checked at boot time. A value of 0 indicates that the file system should not be checked.</p>
<p>This <code>/etc/fstab</code> entry directs the system to mount a device, identified by the specified UUID and formatted as ext4, onto the "/kedar" directory during the boot process. The mount is performed with default options, and there is no requirement for automatic backups or file system checks.</p>
<p>Here are some reasons to use UUID instead of partition name</p>
<ul>
<li><p>Device names (e.g., <code>/dev/sda1</code>) can change, especially in systems with multiple storage devices or when hardware configurations are modified. UUIDs remain constant.</p>
</li>
<li><p>During the boot process, multiple storage devices may be detected simultaneously. UUIDs eliminate the possibility of race conditions, where the operating system may assign different names to the same physical device in different boot instances.</p>
</li>
<li><p>If device names are used in <code>/etc/fstab</code> and names change due to hardware changes, it may lead to mounting errors or data corruption. UUIDs ensure the correct device is always mounted.</p>
</li>
<li><p>UUIDs are more human-readable and less prone to typos than device names, making the <code>/etc/fstab</code> file easier to read and maintain.</p>
</li>
<li><p>UUIDs remain the same when moving a storage device from one system to another, ensuring correct mounting without modifying <code>/etc/fstab</code> for the new system.</p>
</li>
</ul>
<p>Here's an example <code>/etc/fstab</code> entry using UUID:</p>
<pre><code class="lang-bash">UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx /mnt/data ext4 defaults 0 2
</code></pre>
<p>Replace <code>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</code> with the actual UUID of the partition.</p>
<h3 id="heading-how-to-mount-a-partition">How to Mount a Partition</h3>
<p>Once everything is done, we will mount partition on one of your directory.</p>
<pre><code class="lang-bash">mount -av
</code></pre>
<p>If this returns a "successfully mounted" message on <code>kedar</code> directory, then your partition has mounted on <code>kedar</code> directory.</p>
<p>Now every time you turn on your system, the specified partition will automatically be mounted on the "/kedar" directory, ensuring seamless access to its contents throughout your computing sessions.</p>
<p>This persistent mount configuration is facilitated by the entry in the <code>/etc/fstab</code> file, providing a consistent and reliable attachment of the partition during the system's startup process.</p>
<h2 id="heading-how-to-create-logical-partitions">How to Create Logical Partitions</h2>
<p>Logical partitions are a key concept in disk partitioning, especially in systems using the Master Boot Record (MBR) partitioning scheme.</p>
<p>MBR allows for a maximum of four primary partitions, and to overcome this limitation, one of the primary partitions can be designated as an extended partition.</p>
<p>Within the extended partition, multiple logical partitions can then be created.</p>
<h3 id="heading-identify-the-disk"><strong>Identify the Disk</strong></h3>
<p>Begin by identifying the disk where you want to create logical partitions. You can use the <code>lsblk</code> or <code>fdisk -l</code> commands to list the available disks and their partitions</p>
<pre><code class="lang-bash">lsblk
</code></pre>
<h3 id="heading-launch-parted-for-the-disk"><strong>Launch Parted for the Disk</strong></h3>
<p>Use the <code>parted</code> command to launch the interactive interface for the chosen disk (replace 'X' with the appropriate disk identifier):</p>
<pre><code class="lang-bash">parted /dev/sdX
</code></pre>
<h3 id="heading-create-an-extended-partition"><strong>Create an Extended Partition</strong></h3>
<p>If not already created, you need to establish an extended partition within which the logical partitions will reside.</p>
<p>This step is essential as logical partitions can only exist within an extended partition. Assume the free space is from 50% to 100% of the disk:</p>
<pre><code class="lang-bash">(parted) mkpart extended 50% 100%
</code></pre>
<h3 id="heading-create-logical-partitions"><strong>Create Logical Partitions</strong></h3>
<p>Now, within the extended partition, you can create logical partitions. The following example creates a logical partition using <strong>ext4</strong> file system from 0% to 25% of the extended partition.</p>
<p>You can also give size using MB format. For that you need to know the free space. You can do that using <code>print free</code> command inside parted.</p>
<pre><code class="lang-bash">(parted) mkpart logical ext4 0% 25%
</code></pre>
<p>You can repeat this step to create additional logical partitions with different sizes or file systems.</p>
<h3 id="heading-partitioning-scheme-numbering-convention">Partitioning Scheme Numbering Convention</h3>
<p>In the Master Boot Record (MBR) partitioning scheme, the numbering convention for logical partitions within an extended partition typically starts from 5. This is because the four primary partitions (if they exist) are assigned numbers 1 to 4, and logical partitions are numbered starting from 5.</p>
<p>Here's a common numbering scheme:</p>
<ul>
<li><p>Primary Partition 1: <code>/dev/sdX1</code></p>
</li>
<li><p>Primary Partition 2: <code>/dev/sdX2</code></p>
</li>
<li><p>Primary Partition 3: <code>/dev/sdX3</code></p>
</li>
<li><p>Primary Partition 4: <code>/dev/sdX4</code></p>
</li>
<li><p>Extended Partition: <code>/dev/sdX4</code> (the extended partition is counted as one of the four)</p>
</li>
<li><p>Logical Partition 5: <code>/dev/sdX5</code></p>
</li>
<li><p>Logical Partition 6: <code>/dev/sdX6</code></p>
</li>
<li><p>Logical Partition 7: <code>/dev/sdX7</code>, and so on.</p>
</li>
</ul>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>Thank you for exploring how MBR disk partitioning works with me today. You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Linux Boot Process – What Happens when Booting RHEL ]]>
                </title>
                <description>
                    <![CDATA[ The boot process is made up of a series of necessary actions that a computer goes through upon startup. These range from powering on to the complete loading of the operating system (OS) for optimal functionality. It is vital to familiarize yourself w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/linux-boot-process-in-rhel/</link>
                <guid isPermaLink="false">66d45f6b51f567b42d9f8463</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 02 Feb 2024 17:49:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Frame-1000004568.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The boot process is made up of a series of necessary actions that a computer goes through upon startup. These range from powering on to the complete loading of the operating system (OS) for optimal functionality.</p>
<p>It is vital to familiarize yourself with the boot process for various reasons. First of all, having a solid understanding of booting process is crucial for effectively addressing boot issues, enhancing system performance, and efficiently controlling various components of system startup.</p>
<p>For example, it'll help you identify and resolve problems that may arise during the boot process, such as hardware malfunctions or incorrect configurations.</p>
<p>Also, gaining a thorough understanding of the boot process can help you personalize your startup configurations. This includes the ability to select the specific programs or services that are launched upon startup, ultimately affecting both the overall system performance and user satisfaction.</p>
<h2 id="heading-table-of-contents"><strong>Table Of Contents</strong></h2>
<p>Here's what we'll cover in this comprehensive guide:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-high-level-overview-of-the-booting-process">High level overview of the booting process</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-boot-process-in-depth">Understanding the boot process in depth</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-post-power-on-self-test">POST (Power-On Self-Test)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-biosuefi">Understanding BIOS/UEFI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-mbr-master-boot-record">MBR (Master Boot Record)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-gpt-guid-partition-table">GPT (GUID Partition Table)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-grub-grand-unified-boot-loader">GRUB (Grand Unified Boot Loader)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-initrd-initial-ram-disk-image">Initrd (Initial RAM Disk) Image</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-kernel">Kernel</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rootfs">RootFS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-init-process">Init Process</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-system-daemons">System Daemons</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-high-level-overview-of-the-booting-process">High Level Overview of the Booting Process</h2>
<h3 id="heading-initializing-hardware">Initializing Hardware</h3>
<p>During the boot process, the computer's firmware (such as BIOS or UEFI) takes charge and sets up all the necessary hardware components, including the processor, memory, storage devices, and peripherals. This crucial initialization stage guarantees that these components are fully prepared for the operating system's use.</p>
<h3 id="heading-loading-the-operating-system">Loading the Operating System</h3>
<p>Once the hardware has been initialized, the boot process commences with loading the operating system. This step usually consists of loading the kernel and initializing crucial OS services into memory.</p>
<h3 id="heading-launching-system-services">Launching System Services</h3>
<p>As the operating system starts up, it activates a range of system services and drivers. These essential components ensure the smooth operation of the computer, enabling tasks such as managing network connections, processing input/output operations, and maintaining security measures.</p>
<h3 id="heading-user-interaction">User Interaction</h3>
<p>At long last, the boot process reaches its peak by greeting you (the user) with a login screen or desktop environment, granting full access to the computer and its various applications.</p>
<h2 id="heading-understanding-the-boot-process-in-depth">Understanding the Boot Process in Depth</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-150.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Booting Process</em></p>
<h2 id="heading-post-power-on-self-test">POST (Power-On Self-Test)</h2>
<p>When a computer is first turned on, there is a vital process that takes place known as the Power-On Self-Test, or POST for short. This diagnostic testing sequence is conducted by the system's firmware, whether it be BIOS or UEFI, as a crucial step in the booting sequence.</p>
<p>Its main purpose is to verify that all essential hardware components are functioning properly before handing control over to the operating system. In short, POST is a crucial step in ensuring that a computer is ready to operate at its full potential upon startup.</p>
<h3 id="heading-stages-and-functions-of-post">Stages and Functions of POST</h3>
<h4 id="heading-initialization">Initialization</h4>
<p>When the computer is turned on, the system's firmware (BIOS or UEFI) takes control.</p>
<p>The firmware begins by initializing critical hardware components like the CPU, RAM, chipset, and other essential devices.</p>
<h4 id="heading-power-on-self-test-post">Power-On Self-Test (POST)</h4>
<p>The POST sequence begins immediately after initialization. It checks various hardware components by sending test signals and commands to them.</p>
<p>It checks the CPU, RAM (memory), storage devices (hard drives, SSDs), graphics cards, peripherals (keyboard, mouse), and other connected hardware.</p>
<p>Each component is tested to ensure it responds correctly and operates within acceptable parameters.</p>
<ol>
<li><p>The CPU is checked by verifying its operating frequency and executing a simple test.</p>
</li>
<li><p>The RAM is tested by writing and reading data to verify its integrity.</p>
</li>
<li><p>Storage devices are checked for presence and basic functionality.</p>
</li>
<li><p>Peripherals might be tested by checking if they respond to commands.</p>
</li>
</ol>
<p>Any failure during the POST process results in error messages or audible beeps that indicate which component failed the test.</p>
<h4 id="heading-error-handling">Error Handling</h4>
<p>If an error is detected during POST, the system typically halts and displays an error message, or it might emit a series of audible beeps (known as beep codes) indicating the nature of the issue.</p>
<p>Error codes or messages generated during POST are crucial for diagnosing hardware problems. They help in identifying the failing component or area causing the issue.</p>
<h4 id="heading-completion-and-handover">Completion and Handover</h4>
<p>Once the POST sequence completes without detecting any critical errors, the firmware determines that the hardware is functioning correctly.</p>
<p>The firmware proceeds to initialize other system components and search for a boot device to load the operating system.</p>
<h2 id="heading-understanding-biosuefi">Understanding BIOS/UEFI</h2>
<p>BIOS and UEFI are two essential firmware interfaces responsible for initializing hardware components, running system diagnostics, and supporting the startup of the operating system on a computer. These interfaces are vital players in the boot process of a system.</p>
<h3 id="heading-bios">BIOS</h3>
<p>For decades, BIOS has been a dominant firmware interface, stored on the motherboard's chip. Its crucial role is to activate and oversee hardware during the boot-up phase.</p>
<p>As soon as the computer is switched on, the BIOS assumes command and executes the Power-On Self-Test (POST) to ensure the essential hardware components – including the RAM, CPU, and storage devices – are all functioning properly.</p>
<p>After the POST is successfully completed, the BIOS will then proceed to search for the boot device, using a predetermined boot order that was previously set in the BIOS settings. This boot order typically includes popular devices such as hard drives, solid-state drives, optical drives (CD/DVD), USB drives, and network interfaces.</p>
<p>Once the boot device has been identified, the BIOS proceeds to search for either the Master Boot Record (MBR) or the GUID Partition Table (GPT) on the storage device. These contain the crucial initial boot loader code. The BIOS then dutifully passes the reins to the designated boot loader, such as GRUB for Linux operating systems.</p>
<h3 id="heading-uefi-unified-extensible-firmware-interface">UEFI (Unified Extensible Firmware Interface)</h3>
<p>UEFI is a more modern and versatile replacement for BIOS. It provides more advanced features and capabilities than BIOS.</p>
<p>UEFI is firmware that resides on the motherboard and is responsible for initializing hardware and booting the operating system.</p>
<p>Similar to BIOS, UEFI starts with the hardware initialization and system checks. But UEFI supports more modern hardware standards and allows for faster boot times compared to traditional BIOS.</p>
<p>UEFI includes a boot manager, which is more sophisticated than the boot loaders used in BIOS systems. It understands different file systems, allowing the system to boot from drives formatted with newer file systems like GPT. It uses EFI boot partitions to store bootloaders and related information.</p>
<p>UEFI introduced Secure Boot, a security feature that verifies the digital signatures of boot loaders and operating system kernels during the boot process. This helps prevent the loading of unauthorized or malicious code during boot time.</p>
<h3 id="heading-differences-between-bios-and-uefi">Differences between BIOS and UEFI</h3>
<ul>
<li><p>BIOS uses the Master Boot Record (MBR) method, while UEFI uses the GUID Partition Table (GPT) method.</p>
</li>
<li><p>UEFI is more flexible and supports larger storage capacities, modern hardware, and faster boot times compared to BIOS.</p>
</li>
<li><p>UEFI introduces Secure Boot, enhancing system security by verifying the authenticity of bootloader and OS components.</p>
</li>
</ul>
<h2 id="heading-mbr-master-boot-record">MBR (Master Boot Record)</h2>
<p>The Master Boot Record (MBR) plays a vital role in the storage structure of a disk. It is closely linked to BIOS-based systems and serves as the catalyst for the initial booting process.</p>
<h3 id="heading-structure-of-mbr">Structure of MBR</h3>
<p>The MBR is located in the first sector of a storage device (usually the first 512 bytes of a hard drive or SSD). It's in a fixed location, the LBA (Logical Block Address) 0.</p>
<p>The Master Boot Record (MBR) if of 512 bytes in size. It consists of three components:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image--1--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>MBR Structure: Boot signature, partitions, and bootstrap code</em></p>
<ol>
<li><p>The primary boot loader information occupies the initial 446 bytes.</p>
</li>
<li><p>Following that, the partition table information fills the subsequent 64 bytes.</p>
</li>
<li><p>Lastly, the MBR validation check, also known as the magic number, resides in the final 2 bytes.</p>
</li>
</ol>
<p>A partition table is a small database that holds information about the disk's partitions. This table can store information for up to four primary partitions or three primary partitions and one extended partition.</p>
<p>Each entry in the partition table consists of</p>
<ol>
<li><p>Starting and ending addresses of each partition.</p>
</li>
<li><p>Partition type (such as FAT, NTFS, Linux filesystem, and so on).</p>
</li>
<li><p>Bootable flag indicating which partition is the active/bootable partition.</p>
</li>
</ol>
<h3 id="heading-function-of-mbr">Function of MBR</h3>
<p>The MBR boot code's primary function is to locate and load the active/bootable partition's boot loader. It reads the partition table to identify which partition holds the bootable flag and executes the boot loader code from that partition.</p>
<p>The boot loader (for example, GRUB) subsequently takes over and presents a boot menu if configured, allowing the user to choose an operating system to load. It then loads the selected OS's kernel and initiates its booting process.</p>
<h3 id="heading-limitations-of-mbr">Limitations of MBR</h3>
<p>MBR has limitations in supporting only four primary partitions or three primary partitions and one extended partition, which can further contain multiple logical partitions. This restricts the number of partitions usable on a disk.</p>
<p>MBR uses 32-bit addressing, limiting disk sizes to 2 terabytes (TB). Larger disks cannot be fully utilized under MBR due to this limitation.</p>
<p>It also lacks built-in security features, making it susceptible to boot sector viruses or malicious code overwriting the boot loader.</p>
<h2 id="heading-gpt-guid-partition-table">GPT (GUID Partition Table)</h2>
<p>The GUID Partition Table (GPT) is a partitioning scheme used on modern storage devices and is closely associated with UEFI-based systems. It replaced the older Master Boot Record (MBR) partitioning scheme due to its numerous advantages and capabilities, especially in conjunction with UEFI firmware.</p>
<h3 id="heading-structure-of-gpt">Structure of GPT</h3>
<p>GPT is a partitioning scheme that defines the layout of partitions on a storage device. Unlike MBR, which has limitations regarding disk size and partition count, GPT offers more flexibility and scalability.</p>
<p>Each partition in a GPT disk is identified by a unique GUID (Globally Unique Identifier). This allows for up to 128 partitions per disk (though practical limitations might apply based on the operating system and system firmware).</p>
<p>GPT disks contain a Protective MBR to maintain compatibility with legacy systems that may not recognize GPT partitions. This Protective MBR tells older systems that the disk is in use and prevents them from overwriting or modifying the GPT partitions.</p>
<p>GPT stores partition entries in a table located at the beginning and end of the disk. This redundancy enhances data integrity and provides backup information about the partition layout.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>GUID partition table scheme diagram</em></p>
<h3 id="heading-function-of-gpt">Function of GPT</h3>
<p>UEFI requires a specific partition known as the UEFI System Partition (ESP), which is a primary component of the GPT scheme. The ESP contains bootloaders, firmware executables, and other necessary files for the boot process.</p>
<p>UEFI firmware uses information stored in the GPT to locate the UEFI boot loader. The boot loader is stored in the ESP and is specified in the firmware's boot configuration data.</p>
<p>UEFI firmware understands GPT and can read the partition information directly from the GPT header. It uses this information to identify the bootable partition and load the UEFI boot loader from the ESP.</p>
<p>GPT and UEFI work together to support Secure Boot functionality. Secure Boot uses information from GPT to verify the digital signatures of bootloaders and OS components, ensuring a secure boot process.</p>
<p>GPT supports disk sizes larger than 2TB, addressing the limitations of the MBR partitioning scheme. It efficiently manages partitions on larger disks and provides scalability for future storage needs.</p>
<h2 id="heading-grub-grand-unified-boot-loader">GRUB (Grand Unified Boot Loader)</h2>
<p>GRUB stands for Grand Unified Boot Loader. It's a widely used boot loader in the Linux world, responsible for managing the boot process of a computer.</p>
<p>A boot loader is a program that loads the operating system into the computer's memory during the startup process. GRUB is specifically designed for Unix-like operating systems, especially Linux.</p>
<p>GRUB's primary function includes locating the kernel of the chosen operating system and loading it into memory. It also manages the initial RAM disk (initrd/initramfs) that assists the kernel during the boot process.</p>
<p>GRUB uses a configuration file (<code>grub.cfg</code> or <code>menu.lst</code>) where users can define boot options, specify kernel parameters, and customize the appearance of the boot menu. This allows users to modify boot settings or add specific parameters for the operating system to use during startup.</p>
<p>During the installation of Linux distributions, GRUB is usually installed in the Master Boot Record (MBR) of the hard drive or the EFI system partition (for systems using UEFI). This allows GRUB to take control during boot-up and present its menu interface.</p>
<h2 id="heading-initrd-initial-ram-disk-image">Initrd (Initial RAM Disk) Image</h2>
<p>An Initial RAM Disk (initrd), also known as an Initial RAM filesystem (initramfs), is a temporary file system loaded into memory during the boot process of a computer before the main operating system takes over. It's an essential component in modern Linux booting.</p>
<p>The primary purpose of the initrd is to provide a minimal set of tools, drivers, and utilities necessary to mount the root file system. It contains essential drivers for storage controllers, file systems, and other hardware components that the kernel might need to access the actual root file system.</p>
<p>During boot-up, the boot loader (such as GRUB) loads the Linux kernel into memory. The kernel then decompresses itself and, if configured to use an initrd, loads the initrd image as a temporary root file system into a predetermined memory location.</p>
<p>Once the initrd is in place, the kernel executes the code within the initrd. This code performs various tasks like loading essential drivers (for example, for disk controllers, file systems, and so on), initializing hardware, and performing necessary checks to prepare the system to transition to the actual root file system.</p>
<p>After the kernel initializes and detects hardware, the initrd's job is largely complete. It hands control over to the main kernel, which then unmounts the initrd and mounts the actual root file system (specified by the bootloader or kernel parameters).</p>
<p>Traditionally, initrd was used, but modern systems often use initramfs (a more flexible successor). Initramfs is a cpio archive that is uncompressed into a RAM disk at boot time. It's more versatile, allowing for a more modular approach to including essential files and drivers.</p>
<h2 id="heading-kernel">Kernel</h2>
<p>The kernel is the core of the operating system, managing hardware resources, providing abstractions, and controlling interactions between hardware and software.</p>
<p>After the initrd image completes its tasks, the kernel takes control. It initializes the system hardware, mounts the root file system, and begins the user-space initialization process.</p>
<p>The kernel uses information provided by the initrd to mount the actual root file system (for example, ext4, XFS) specified in the boot parameters.</p>
<h2 id="heading-rootfs">RootFS</h2>
<p>The Root File System (rootfs) is a critical component in the booting process of an operating system. It is the top-level directory hierarchy of the file system and contains essential system files and directories.</p>
<p>In the context of the booting process, the root file system is the initial file system that the operating system kernel mounts during the boot sequence.</p>
<p>The root file system is the starting point for the entire file system hierarchy. It is mounted by the kernel during the boot process, and all other file systems are mounted as subdirectories of the root file system.</p>
<p>The bootloader, such as GRUB in many Linux systems, is configured to specify the location of the root file system. This information is crucial for the kernel to know where to find the core files and directories needed to start the operating system.</p>
<p>The root file system can be of different types, such as ext4, XFS, or other supported file systems. The choice of the file system type depends on the system administrator's preferences and requirements.</p>
<p>In some cases, especially in complex storage scenarios (for example, RAID or LVM configurations), an initial RAM disk (initramfs) is used. The initramfs provides necessary modules and tools for the kernel to initialize and mount the root file system. Afterward, the kernel switches to the actual root file system.</p>
<p>The root file system contains critical directories such as <code>/bin</code>, <code>/etc</code>, <code>/sbin</code>, and <code>/lib</code>. These directories house essential binaries, configuration files, system libraries, and scripts required for system operation.</p>
<p>The root file system is typically a persistent file system stored on a storage device like a hard drive or an SSD. It retains data and configurations across reboots, ensuring a consistent environment for the operating system.</p>
<p>The stability and functionality of the operating system depend on the successful initialization and mounting of the root file system. It provides the foundation for the entire operating system environment.</p>
<h2 id="heading-init-process">Init Process</h2>
<p>The init process, short for initialization, is a fundamental part of the booting process in Unix-like operating systems, including many Linux distributions. Its primary responsibility is to initialize the system and bring it to a functional state by starting various system services and user-space processes.</p>
<p>After the kernel has loaded and initialized, it hands over control to the init process. The kernel command-line parameters or configuration files specify the process to which control should be transferred.</p>
<p>Traditional Unix systems used the init process with different runlevels, where each runlevel represented a different system state. But modern Linux systems, including those based on Red Hat Enterprise Linux (RHEL), have transitioned to using systemd, which serves as a replacement for init and introduces a more flexible and efficient approach to managing system initialization.</p>
<p>On modern Linux systems like RHEL, systemd has become the default init system. It initializes the system in parallel, improving boot times and system responsiveness. systemd reads its configuration from unit files located in directories such as <code>/etc/systemd/system</code> and <code>/usr/lib/systemd/system</code>.</p>
<p>The init process, whether traditional init or systemd, is responsible for starting system services and daemons. These services provide essential functionality to the operating system, such as networking, logging, and hardware-related services.</p>
<h2 id="heading-system-daemons">System Daemons</h2>
<p>System daemons, also known as background processes or services, play a vital role in the booting process and ongoing operation of Unix-like operating systems, including those based on Red Hat Enterprise Linux (RHEL). These daemons are specialized programs that run in the background, providing essential services to the system and users.</p>
<p>A daemon is a background process that runs independently of user interaction. Daemons perform specific tasks, such as managing hardware, handling system events, or providing network services.</p>
<p>During the boot process, the init or systemd process is responsible for starting system daemons. These daemons are configured to launch automatically at specific runlevels (in the case of traditional init) or as defined in systemd unit files.</p>
<p>Daemons are typically initialized by the init or systemd process as part of the system startup. The initialization process may involve reading configuration files, setting up communication channels, and allocating resources.</p>
<p>Examples of system daemons include:</p>
<ul>
<li><p><strong>Network services:</strong> Daemons like <code>sshd</code> for secure shell access, <code>httpd</code> for web services, and <code>dhcpd</code> for dynamic host configuration protocol.</p>
</li>
<li><p><strong>Logging services:</strong> <code>rsyslogd</code> or <code>syslog-ng</code> for handling system logs.</p>
</li>
<li><p><strong>Time synchronization:</strong> <code>ntpd</code> for Network Time Protocol (NTP) synchronization.</p>
</li>
<li><p><strong>Printing services:</strong> <code>cupsd</code> for Common Unix Printing System.</p>
</li>
<li><p><strong>Hardware management:</strong> <code>udev</code> for device management and <code>acpid</code> for Advanced Configuration and Power Interface events.</p>
</li>
</ul>
<p>The init or systemd process manages dependencies between daemons. It ensures that daemons relying on specific resources or services are started in the correct order to satisfy these dependencies.</p>
<p>systemd, in particular, introduces parallel initialization, meaning that multiple daemons and services can be started simultaneously, improving boot times by taking advantage of modern multi-core systems.</p>
<p>Once system daemons are initialized, the system is ready to handle user interactions. For example, network services are available, and users can log in or access various system resources.</p>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>Thank you for exploring booting process in RHEL with me today. You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Job Scheduling in RHEL – cron and at Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Efficiently executing tasks at designated times or in response to certain events is essential in RHEL's job scheduling process. With the help of various tools and utilities, you can easily coordinate and automate job scheduling, eliminating the need ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/job-scheduling-in-rhel/</link>
                <guid isPermaLink="false">66d45f69d14641365a0508f9</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Mon, 29 Jan 2024 14:06:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Frame-1000004567.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Efficiently executing tasks at designated times or in response to certain events is essential in RHEL's job scheduling process. With the help of various tools and utilities, you can easily coordinate and automate job scheduling, eliminating the need for manual intervention.</p>
<p>Some common tools for job scheduling in RHEL include:</p>
<ul>
<li><p>cron: A time-based job scheduler in Unix-like operating systems. Users can schedule repetitive tasks by creating entries in the crontab file, specifying when and how frequently these tasks should run.</p>
</li>
<li><p>at: The <code>at</code> command allows users to schedule one-time jobs to be executed at a specified time in the future.</p>
</li>
</ul>
<h2 id="heading-table-of-contents"><strong>Table Of Contents</strong></h2>
<p>Here's what we'll cover in this comprehensive guide:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-deamon">What is a deamon</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-systemctl">What is systemctl</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-job-scheduling-using-at">Job Scheduling using at</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-job-scheduling-using-crontab">Job Scheduling using crontab</a></p>
</li>
<li><p><a class="post-section-overview" href="#practical-exercise">Practical Exercises</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-deamon">What is a Deamon?</h2>
<p>In Red Hat Enterprise Linux (RHEL) and other Unix-like operating systems, a "daemon" is a background process that runs continuously, typically providing specific services or functionality to the operating system or applications.</p>
<p>Daemons are frequently responsible for handling various tasks such as hardware management, responding to network requests, executing scheduled tasks, and facilitating communication between different software components.</p>
<p>These tasks do not typically require direct user involvement and are usually carried out without user intervention.</p>
<p>Common examples of daemons include web servers (like Apache or NGINX), database servers (such as MySQL or PostgreSQL), and system services (like cron for scheduling tasks or systemd for managing various system services).</p>
<h2 id="heading-what-is-systemctl">What is <code>systemctl</code>?</h2>
<p>Systemctl is an essential in Red Hat Enterprise Linux (RHEL) that empowers users to control and oversee their systemd system and service manager with ease.</p>
<p>This command-line utility offers a seamless way to interface with the systemd init system, which plays a crucial role in booting the operating system, supervising services, and managing a range of system functionalities.</p>
<p>Let's take a closer look at what this tool can do:</p>
<h3 id="heading-service-management">Service Management</h3>
<h4 id="heading-starting-and-stopping-services">Starting and Stopping Services</h4>
<ul>
<li><code>systemctl start service_name</code> initiates a service. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl start atd
</code></pre>
<p>The above command <code>systemctl start atd</code> is used in Linux systems to start the <code>atd</code> (which stands for "AT Daemon") service using the <code>systemctl</code> utility.</p>
<ul>
<li><code>systemctl stop service_name</code> stops a service. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl stop atd
</code></pre>
<p>By running <code>systemctl stop atd</code>, you're instructing the system to stop the <code>atd</code> service. As a result, any tasks or jobs scheduled to run using the <code>at</code> command will not be processed until the service is started again.</p>
<h4 id="heading-enabling-and-disabling-services">Enabling and Disabling Services</h4>
<ul>
<li><code>systemctl enable service_name</code> sets a service to start automatically at boot. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">enable</span> crond
</code></pre>
<p>This code sets the <code>crond</code> service to start automatically every time the system boots up. This ensures that the cron service, responsible for handling scheduled tasks, is active and ready to execute commands at their specified times without requiring manual intervention after each system restart.</p>
<ul>
<li><code>systemctl disable service_name</code> prevents a service from starting automatically at boot. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">disable</span> crond
</code></pre>
<p>Executing above command removes the configuration that enables the <code>crond</code> service to start up automatically when the system boots. As a result, after a system reboot, the <code>crond</code> service will not be initiated automatically. Users will need to manually start the service if they want to use cron for scheduling tasks.</p>
<h3 id="heading-viewing-service-status">Viewing Service Status</h3>
<h4 id="heading-checking-service-status">Checking Service Status</h4>
<ul>
<li><code>systemctl status service_name</code> displays the current status and information about a service. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl status crond
</code></pre>
<p>This provides information about whether the <code>crond</code> service is running, stopped, or encountering any issues. It typically includes details such as whether the service is active or inactive, when it was last started or stopped, and any error messages or warnings related to its operation.</p>
<h4 id="heading-displaying-all-services">Displaying All Services</h4>
<ul>
<li><code>systemctl list-units --type=service</code> lists all active services. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl list-units --<span class="hljs-built_in">type</span>=service
</code></pre>
<p>This provides a comprehensive list of all services—both active and inactive—managed by <code>systemd</code> on the system. This output includes information such as the unit name, load status, active status (whether it's running or not), and description of each service.</p>
<p>All possible Service Management <code>systemctl</code> commands are listed below. You can explore all of them on your own to get a better understanding of how they work.</p>
<pre><code class="lang-bash">systemctl start &lt;service&gt;: Starts a service.

systemctl stop &lt;service&gt;: Stops a service.

systemctl restart &lt;service&gt;: Restarts a service.

systemctl reload &lt;service&gt;: Reloads configuration <span class="hljs-keyword">for</span> a service without stopping it.

systemctl status &lt;service&gt;: Displays the current status and information about a service.

systemctl <span class="hljs-built_in">enable</span> &lt;service&gt;: Enables a service to start automatically at boot.

systemctl <span class="hljs-built_in">disable</span> &lt;service&gt;: Disables a service from starting automatically at boot.

systemctl is-active &lt;service&gt;: Checks <span class="hljs-keyword">if</span> a service is currently running.

systemctl is-enabled &lt;service&gt;: Checks <span class="hljs-keyword">if</span> a service is enabled to start at boot.

systemctl is-failed &lt;service&gt;: Checks <span class="hljs-keyword">if</span> a service has failed.
</code></pre>
<h3 id="heading-system-control">System Control</h3>
<h4 id="heading-rebooting-and-shutting-down">Rebooting and Shutting Down</h4>
<ul>
<li><code>systemctl reboot</code> restarts the system. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl reboot
</code></pre>
<p>This shuts down the operating system, terminating all running processes and services, and then starts the boot process again. It brings the system back to a fresh start.</p>
<ul>
<li><code>systemctl poweroff</code> shuts down the system. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl poweroff
</code></pre>
<p>This triggers a series of actions that include shutting down all running services and processes in an orderly manner, saving any necessary data, and finally turning off the system.</p>
<h4 id="heading-suspending-and-hibernating">Suspending and Hibernating</h4>
<ul>
<li><code>systemctl suspend</code> puts the system into a suspend state. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">suspend</span>
</code></pre>
<p>This triggers the system to enter a suspended state. In this state, the system effectively halts most operations, including the CPU and other hardware components, to conserve power.</p>
<p>But it keeps the current system state in memory (RAM) so that when it's resumed, the system can quickly return to its previous state without a full boot-up process.</p>
<ul>
<li><code>systemctl hibernate</code> puts the system into hibernation. Here's an example:</li>
</ul>
<pre><code class="lang-bash">systemctl hibernate
</code></pre>
<p>It saves everything you're doing on your computer onto the hard drive and then turns off the computer completely. When you start it up again, it brings back exactly what you were working on before, just like you left it. This is different from "suspend," which keeps your work in a low-power mode but still on.</p>
<h3 id="heading-viewing-system-information">Viewing System Information</h3>
<h4 id="heading-displaying-system-logs">Displaying System Logs</h4>
<ul>
<li><code>journalctl</code> views system logs and journal entries. Here's an example:</li>
</ul>
<pre><code class="lang-bash">journalctl
</code></pre>
<p>This displays logs that include system messages, kernel messages, service logs, and other events recorded by the system.</p>
<ul>
<li><code>journalctl -u &lt;unit&gt;</code> displays logs for a specific unit. Here's an example:</li>
</ul>
<pre><code class="lang-bash">journalctl -u crond
</code></pre>
<p>You'll see logs that are related to the <code>crond</code> service specifically. This includes messages, errors, or other information logged by the <code>crond</code> daemon, which is responsible for managing scheduled tasks using the cron job scheduler.</p>
<ul>
<li><code>journalctl --since=&lt;time&gt;</code> shows logs since a specific time. Here's an example:</li>
</ul>
<pre><code class="lang-bash">journalctl --since <span class="hljs-string">"2024-01-01 08:00:00"</span>
</code></pre>
<p>This retrieves and displays system logs that have been generated or recorded after January 1st, 2023, at 8:00 AM. This helps in narrowing down the logs to view system events or messages that occurred from that specific point in time onwards, and can help you troubleshoot or analyze recent system activity.</p>
<p>These commands of <code>systemctl</code> are enough to start a job scheduling module. You can always explore more <code>systemctl</code> commands on your own.</p>
<h2 id="heading-job-scheduling-using-at">Job Scheduling using <code>at</code></h2>
<p>The <code>at</code> command is used for scheduling one-time tasks or commands that will be carried out at a designated future time. This feature is especially useful for automating tasks that you need to complete at a later time, so you don't have to remember to do them later.</p>
<p>To use <code>at</code>, you'll need to check the following:</p>
<ul>
<li><p>Ensure that the <code>at</code> daemon (<code>atd</code>) is running for <code>at</code> jobs to execute. You can use the <code>systemctl</code> command to check if <code>atd</code> is running or not. If not, you can use <code>systemctl</code> to start it (and you can see how to do that in the <code>systemctl</code> section in this tutorial).</p>
</li>
<li><p>Permissions might be restricted for non-admin users to use <code>at</code>, depending on system settings.</p>
</li>
<li><p>If you are manipulating something in a file, make sure you have Read-Write-Execute permission for that same file.</p>
</li>
</ul>
<h3 id="heading-syntax-of-at">Syntax of <code>at</code></h3>
<pre><code class="lang-bash">at &lt;time&gt;
</code></pre>
<h3 id="heading-examples-of-using-the-at-command">Examples of using the <code>at</code> command</h3>
<p>Let's see how the <code>at</code> command works in practice with a few examples.</p>
<p>First, here's how you can display a message at a specific time:</p>
<pre><code class="lang-bash">at 15:35
</code></pre>
<p>Now let's say you need to give commands that will run automatically at 15:35:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Meeting in 30 minutes"</span> &gt;&gt; sample.txt
</code></pre>
<p>Press <code>Ctrl + D</code> to finish entering commands and schedule the job. This will print "Meeting in 30 minutes" in sample.txt file at 15:35.</p>
<p>Perhaps you have a script named <code>backup.sh</code> and you want it to run at 2 AM. Here's how you'd do that:</p>
<pre><code class="lang-bash">at -f backup.sh 02:00
</code></pre>
<p>This code schedules the <code>backup.sh</code> script to run at 2:00 AM. The contents of <code>backup.sh</code> will be executed as if they were entered directly into the terminal at that specified time.</p>
<p>You can also use the following command to see a list of pending <code>at</code> jobs:</p>
<pre><code class="lang-bash">atq
</code></pre>
<p>The <code>atq</code> command helps you view and manage a list of pending <code>at</code> jobs, letting you easily reference scheduled tasks and their execution times.</p>
<p>Here's some example output of the <code>atq</code> command:</p>
<pre><code class="lang-bash">10    Wed Jan 12 03:00:00 2023 a user123
</code></pre>
<ul>
<li><p>The first column represents the job number.</p>
</li>
<li><p>The second column shows the scheduled execution time for each job.</p>
</li>
<li><p>The third column denotes the priority level ('a' in this case).</p>
</li>
<li><p>'a' is usually the default priority level assigned to <code>at</code> jobs, and as the letters move down the alphabet ('b', 'c', 'd', and so forth), the priority level decreases.</p>
</li>
<li><p>The fourth column displays the username of the user who scheduled the job (if available).</p>
</li>
</ul>
<p>Here's how to remove a job:</p>
<pre><code class="lang-bash">atrm 10
</code></pre>
<p>The above code removes the <code>at</code> job with the ID number '3' from the <code>at</code> queue, preventing it from being executed at its scheduled time. You can find job Id by <code>atq</code> command. Job Id is in the 1st column of output.</p>
<h3 id="heading-atallow-and-atdeny"><code>at.allow</code> and <code>at.deny</code></h3>
<p>The files <code>at.allow</code> and <code>at.deny</code> are used to control access for users to schedule jobs using <code>at</code>. These files are typically located in <code>/etc/</code> in RHEL.</p>
<p>The <code>at.allow</code> file specifies the list of users who are allowed to use the <code>at</code> command to schedule jobs. If this file exists, only users listed in it can schedule <code>at</code> jobs. If the file doesn't exist, it behaves as if it's empty, allowing all users unless restricted by <code>at.deny</code>.</p>
<p>The <code>at.deny</code> file specifies the list of users who are denied access to use the <code>at</code> command. If this file exists and a user is listed in it, that user won't be able to schedule <code>at</code> jobs.</p>
<p>If both <code>at.allow</code> and <code>at.deny</code> exist, <code>at.allow</code> takes precedence. If neither exists, only the superuser (root) can schedule <code>at</code> jobs.</p>
<h4 id="heading-managing-access-summary-and-recap">Managing Access – summary and recap</h4>
<ul>
<li><p>If <code>at.allow</code> exists, only users listed in this file can use <code>at</code>.</p>
</li>
<li><p>If <code>at.deny</code> exists but <code>at.allow</code> doesn't, users not listed in <code>at.deny</code> can use <code>at</code>.</p>
</li>
<li><p>If neither <code>at.allow</code> nor <code>at.deny</code> exists, by default, only the superuser (root) can use <code>at</code>.</p>
</li>
</ul>
<h4 id="heading-examples-of-atallow-and-atdeny">Examples of <code>at.allow</code> and <code>at.deny</code></h4>
<p>Let's say you want to restrict <code>at</code> usage to specific users:</p>
<p>Create an <code>at.allow</code> file like this:</p>
<pre><code class="lang-bash">sudo touch /etc/at.allow 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user1"</span> &gt;&gt; /etc/at.allow 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user2"</span> &gt;&gt; /etc/at.allow
</code></pre>
<p>This allows only <code>user1</code> and <code>user2</code> to schedule <code>at</code> jobs.</p>
<p>Alternatively, you can use the <code>at.deny</code> file like this:</p>
<pre><code class="lang-bash">sudo touch /etc/at.deny 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user3"</span> &gt;&gt; /etc/at.deny
</code></pre>
<p>This denies access to <code>user3</code> from using <code>at</code>.</p>
<h2 id="heading-job-scheduling-using-crontab">Job Scheduling using <code>crontab</code></h2>
<p>Cron enables users to schedule recurring actions and commands at specific times, dates, or intervals. This powerful job scheduler stores all the scheduling information in a special file known as the <code>crontab</code>.</p>
<h3 id="heading-basic-crontab-commands">Basic crontab Commands</h3>
<ul>
<li><p><code>crontab -e</code>: Opens the user's crontab file in an editor to add or edit cron jobs.</p>
</li>
<li><p><code>crontab -l</code>: Lists the user's cron jobs.</p>
</li>
<li><p><code>crontab -r</code>: Removes all of the user's cron jobs.</p>
</li>
</ul>
<p>A few things to note about <code>crontab</code>:</p>
<ul>
<li><p>Each user can have their own <code>crontab</code>.</p>
</li>
<li><p>The <code>cron</code> daemon (<code>crond</code>) must be running for cron jobs to execute.</p>
</li>
<li><p>Always use absolute paths for scripts and commands within cron jobs.</p>
</li>
</ul>
<h3 id="heading-crontab-format"><code>crontab</code> Format</h3>
<p>The <code>crontab</code> file has five fields followed by the command/script to execute. Here's what it looks like:</p>
<pre><code class="lang-bash">* * * * * command_to_execute
- - - - -
| | | | |
| | | | +----- Day of the week (0 - 7) (Sunday is 0 or 7)
| | | +------- Month (1 - 12)
| | +--------- Day of the month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)
</code></pre>
<p>If you forgot the <code>crontab</code> format, you can always run <code>cat /etc/crontab</code> command and it will display the format for you.</p>
<h3 id="heading-examples-of-using-crontab">Examples of using <code>crontab</code></h3>
<h4 id="heading-run-a-script-every-hour">Run a script every hour</h4>
<pre><code class="lang-bash">crontab -e
</code></pre>
<p>The above command will open the editor with Vim or any other you have set. In that editor, you'll write the job based on the <code>crontab</code> format just like below:</p>
<pre><code class="lang-bash">0 * * * * /path/to/script.sh
</code></pre>
<ul>
<li><p><code>0</code> represents the minute field. In this case, it's set to <code>0</code>, indicating that the cron job will trigger when the minute is <code>0</code>, that is at the start of every hour.</p>
</li>
<li><p><code>*</code> (asterisks) indicates that every possible value for that field is valid. So, <code>* * * * *</code> means the job will run every minute of every hour, every day, every month, and every day of the week.</p>
</li>
<li><p>Putting it all together, the cron job <code>0 * * * * /path/to/script.sh</code> signifies that the script located at <code>/path/to/script.sh</code> will run every hour at the beginning of the hour (when the minute is <code>0</code>).</p>
</li>
</ul>
<h4 id="heading-run-a-command-at-specific-times">Run a command at specific times</h4>
<p>First run <code>crontab -e</code>.</p>
<pre><code class="lang-bash">0 15 * * * command_to_execute
</code></pre>
<ul>
<li><p><code>0</code> represents the minute field. In this case, it's set to <code>0</code>, indicating that the cron job will trigger at the start of the hour.</p>
</li>
<li><p><code>15</code> represents the hour field. It's set to <code>15</code>, which means the job will execute at the 15th hour of the day, that is 3:00 PM.</p>
</li>
</ul>
<p><code>* * * * *</code>: The asterisks denote every possible value for each time-related field. In this case:</p>
<ul>
<li><p><code>*</code> for the day of the month and month fields means it applies to every day of every month.</p>
</li>
<li><p><code>*</code> for the day of the week field means it applies to every day of the week.</p>
</li>
<li><p><code>command_to_execute</code> represents the command or script that will be executed at the specified time. This placeholder should be replaced with the actual command you want to run at 3:00 PM daily.</p>
</li>
</ul>
<h4 id="heading-run-a-job-every-weekday">Run a job every weekday</h4>
<p>First do <code>crontab -e</code>.</p>
<pre><code class="lang-bash">0 9 * * 1-5 command_to_execute
</code></pre>
<p>The above code specifies that the <code>command_to_execute</code> will run at 9:00 AM from Monday to Friday. This cron job is useful for scheduling tasks that should only run on weekdays at a specific time.</p>
<h4 id="heading-run-a-job-every-15-minutes">Run a job every 15 minutes</h4>
<p>First do <code>crontab -e</code>.</p>
<pre><code class="lang-bash">*/15 * * * * command_to_execute
</code></pre>
<p>This specifies that the <code>command_to_execute</code> will run at 0, 15, 30, and 45 minutes past every hour, every day, every month, and every day of the week. This cron job is useful for scheduling tasks that need to be executed in regular intervals, in this case, every 15 minutes.</p>
<h3 id="heading-cronallow-and-crondeny"><code>cron.allow</code> and <code>cron.deny</code></h3>
<p>You use these <code>cron.allow</code> and <code>cron.deny</code> files to control which users are allowed to use the <code>cron</code> service to schedule periodic jobs. These files are typically located in <code>/etc/</code> in RHEL.</p>
<p>The <code>cron.allow</code> file specifies the list of users who are allowed to use the <code>cron</code> service to schedule jobs using <code>crontab</code>. If this file exists, only users listed in it can create <code>crontab</code> entries. If the file doesn't exist, it behaves as if it's empty, allowing all users unless restricted by <code>cron.deny</code>.</p>
<p>The <code>cron.deny</code> file specifies the list of users who are denied access to use the <code>cron</code> service. If this file exists and a user is listed in it, that user won't be able to create <code>crontab</code> entries. If both <code>cron.allow</code> and <code>cron.deny</code> exist, <code>cron.allow</code> takes precedence. If neither exists, only the superuser (root) can create <code>crontab</code> entries.</p>
<h4 id="heading-managing-access-summary">Managing access – summary</h4>
<ul>
<li><p>If <code>cron.allow</code> exists, only users listed in this file can create <code>crontab</code> entries.</p>
</li>
<li><p>If <code>cron.deny</code> exists but <code>cron.allow</code> doesn't, users not listed in <code>cron.deny</code> can create <code>crontab</code> entries.</p>
</li>
<li><p>If neither <code>cron.allow</code> nor <code>cron.deny</code> exist, by default, only the superuser (root) can create <code>crontab</code> entries.</p>
</li>
</ul>
<h4 id="heading-example-of-using-cronallow-and-crondeny">Example of using <code>cron.allow</code> and <code>cron.deny</code></h4>
<p>Let's say you want to restrict <code>cron</code> usage to specific users.</p>
<p>Create a <code>cron.allow</code> file:</p>
<pre><code class="lang-bash">sudo touch /etc/cron.allow 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user1"</span> &gt;&gt; /etc/cron.allow 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user2"</span> &gt;&gt; /etc/cron.allow
</code></pre>
<p>This allows only <code>user1</code> and <code>user2</code> to create <code>crontab</code> entries.</p>
<p>Alternatively, you can use the <code>cron.deny</code> file:</p>
<pre><code class="lang-bash">sudo touch /etc/cron.deny 
sudo <span class="hljs-built_in">echo</span> <span class="hljs-string">"user3"</span> &gt;&gt; /etc/cron.deny
</code></pre>
<p>This denies access to <code>user3</code> from creating <code>crontab</code> entries.</p>
<h2 id="heading-practical-exercises">Practical Exercises</h2>
<h3 id="heading-service-management-with-systemctl">Service Management with <code>systemctl</code></h3>
<ul>
<li><p>Review the current status of system services using <code>systemctl</code>.</p>
</li>
<li><p>Start, stop, enable, or disable a service to understand their functionalities.</p>
</li>
</ul>
<h3 id="heading-scheduling-immediate-tasks-with-at">Scheduling Immediate Tasks with <code>at</code></h3>
<ul>
<li><p>Use <code>at</code> command to schedule an immediate one-time task (e.g., echoing a message, executing a command) to run a few minutes from the current time.</p>
</li>
<li><p>Check the access permissions for <code>at</code> commands by understanding the functionality of <code>at.allow</code> and <code>at.deny</code>.</p>
</li>
</ul>
<h3 id="heading-setting-up-atallow-and-atdeny">Setting Up <code>at.allow</code> and <code>at.deny</code></h3>
<ul>
<li><p>Create an <code>at.allow</code> file to specify users allowed to use <code>at</code> by listing usernames (if it doesn't exist).</p>
</li>
<li><p>Create an <code>at.deny</code> file to restrict users from using <code>at</code> by listing usernames (if necessary).</p>
</li>
<li><p>Try to schedule an <code>at</code> task using different user accounts to observe the effect of these files.</p>
</li>
</ul>
<h3 id="heading-recurring-tasks-with-cron">Recurring Tasks with <code>cron</code></h3>
<ul>
<li><p>Open the crontab using <code>crontab -e</code>.</p>
</li>
<li><p>Schedule a task to run at a specific time each day or week using <code>cron</code>.</p>
</li>
<li><p>Check the access permissions for <code>cron</code> commands by understanding the functionality of <code>cron.allow</code> and <code>cron.deny</code>.</p>
</li>
</ul>
<h3 id="heading-setting-up-cronallow-and-crondeny">Setting Up <code>cron.allow</code> and <code>cron.deny</code></h3>
<ul>
<li><p>Create a <code>cron.allow</code> file to specify users allowed to use <code>cron</code> by listing usernames (if it doesn't exist).</p>
</li>
<li><p>Create a <code>cron.deny</code> file to restrict users from using <code>cron</code> by listing usernames (if necessary).</p>
</li>
<li><p>Attempt to modify or create a <code>cron</code> job using different user accounts to observe the effect of these files.</p>
</li>
</ul>
<h3 id="heading-observation-and-verification">Observation and Verification</h3>
<ul>
<li><p>Monitor the status of scheduled tasks using respective commands (<code>atq</code>, <code>crontab -l</code>).</p>
</li>
<li><p>Validate access restrictions and permissions for <code>at</code> and <code>cron</code> commands by observing user attempts and access denials.</p>
</li>
</ul>
<h3 id="heading-cleanup-and-exploration">Cleanup and Exploration</h3>
<ul>
<li><p>Remove or modify the access control files (<code>at.allow</code>, <code>at.deny</code>, <code>cron.allow</code>, <code>cron.deny</code>) and observe the changes in command accessibility.</p>
</li>
<li><p>Explore additional <code>systemctl</code>, <code>at</code>, and <code>cron</code> commands to deepen your understanding of task scheduling and access control.</p>
</li>
</ul>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>Thank you for exploring the world of Red Hat Enterprise Linux (RHEL) administration with me today. You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How File Ownership and Permissions Work in RHEL ]]>
                </title>
                <description>
                    <![CDATA[ Linux commands give you precise control over file ownership and permissions, ensuring data security and access control. This guide will delve into several essential commands: chown, chgrp, chmod, and umask. The examples will showcase their functional... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/file-ownership-permissions-rhel/</link>
                <guid isPermaLink="false">66d45f65246e57ac83a2c779</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2024 20:56:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/file-ownership-permissions-rhel-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Linux commands give you precise control over file ownership and permissions, ensuring data security and access control.</p>
<p>This guide will delve into several essential commands: <code>chown</code>, <code>chgrp</code>, <code>chmod</code>, and <code>umask</code>. The examples will showcase their functionality, variations, and practical applications.</p>
<h2 id="heading-table-of-contents"><strong>Table Of Contents</strong></h2>
<p>Here's what we'll cover in this comprehensive guide</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-ls-l-view-file-permissions">ls -l – View File Permissions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chown-change-file-ownership">chown – Change File Ownership</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chgrp-change-file-group-ownership">chgrp – Change File Group Ownership</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chmod-modify-file-permissions">chmod – Modify File Permissions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-access-control-lists">Access Control Lists</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-umask-command">The umask Command</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-exercises">Practical Exercise</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-ls-l-view-file-permissions"><code>ls -l</code> – View File Permissions</h2>
<p>In the world of Red Hat Enterprise Linux, using the <code>ls -l</code> command is like taking a peek into a directory's secret diary. It's a way to get a detailed, up-close look at what's inside, almost like flipping through a catalog with all the nitty-gritty details.</p>
<h3 id="heading-ls-l-example"><code>ls -l</code> example</h3>
<p>Running this command displays file permissions, ownership, and other details for files in the current directory.</p>
<pre><code class="lang-bash">ls -l /mydirectory
</code></pre>
<p>Here's the output:</p>
<pre><code class="lang-bash">OUTPUT

drwxr-xr-x 2 username group 4096 Jan 5 09:30 mydirectory
</code></pre>
<p>Let's break down this output part by part. Here's an illustration that shows what each part represents, and I'll go through it in detail below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Frame-1000004565.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Detail output for ls -l command</em></p>
<ul>
<li><p>File Type and Permissions: The first column represents the file type and permissions. It consists of ten characters:</p>
</li>
<li><p>The first character indicates the file type (<code>-</code> for a regular file, <code>d</code> for a directory, <code>l</code> for a symbolic link, and so on.).</p>
</li>
<li><p>The next nine characters represent permissions for the owner, group, and others (read, write, execute).</p>
</li>
<li><p>Number of Links: The second column shows the number of hard links to the file or directory.</p>
</li>
<li><p>Owner and Group: The third and fourth columns display the owner and group associated with the file or directory.</p>
</li>
<li><p>File Size: The fifth column indicates the size of the file in bytes.</p>
</li>
<li><p>Last Modified Time: The sixth column shows the timestamp of the last modification.</p>
</li>
<li><p>File or Directory Name: The final column lists the file or directory name.</p>
</li>
</ul>
<h2 id="heading-chown-change-file-ownership"><code>chown</code> – Change File Ownership</h2>
<p>In Red Hat Enterprise Linux (RHEL), the mighty <code>chown</code> command stands for "change owner" and lets users to modify the ownership of files and directories. This versatile tool is a valuable resource for system administrators in effectively managing permissions and access control.</p>
<h3 id="heading-syntax-of-chown">Syntax of <code>chown</code>:</h3>
<pre><code class="lang-bash">chown [OPTIONS] [NEW_OWNER][:NEW_GROUP] FILE(s)/DIRECTORY(s)
</code></pre>
<p>Options:</p>
<ul>
<li><p>R, <code>--recursive</code>: Recursively change ownership of directories and their contents.</p>
</li>
<li><p>v, <code>--verbose</code>: Display a message for each file processed.</p>
</li>
</ul>
<p>Note: Only the root user or a user with appropriate permissions can use chown to change ownership.</p>
<h3 id="heading-chown-examples"><code>chown</code> examples:</h3>
<p>Changing file ownership:</p>
<pre><code class="lang-bash">chown newowner myfile.txt
</code></pre>
<p>This will change the owner of a file to <code>newowner</code>.</p>
<p>Changing group ownership:</p>
<pre><code class="lang-bash">chown :newgroup myfile.txt
</code></pre>
<p>This command makes a file called <code>myfile.txt</code> join a new group named <code>newgroup</code>, and it doesn't mess with the person who owns the file. You can do this group change using a command called <code>chown</code>. Oh, and there's another special command just for switching groups that we'll talk about soon.</p>
<p>Changing both owner and group:</p>
<pre><code class="lang-bash">chown newowner:newgroup myfile.txt
</code></pre>
<p>This changes the owner to <code>newowner</code> and group to <code>newgroup</code> for the file myfile.txt.</p>
<p>Recursive change (applying changes to subdirectories):</p>
<pre><code class="lang-bash">chown -R newowner:newgroup /path/to/directory
</code></pre>
<p>The above command is instructing the system to change the ownership of all files and directories within the specified directory and its subdirectories to the specified new owner and group. This ensures that the operation is performed recursively across the entire directory structure.</p>
<p>Verbose mode:</p>
<pre><code class="lang-bash">chown -v newowner:newgroup myfile.txt
</code></pre>
<p>The command is instructing the system to change the ownership of the specified file, providing a detailed output of the modifications made. The detailed output is shown because we are using <code>-v</code> option with <code>chown</code>.</p>
<p>Ownership by UID/GID:</p>
<pre><code class="lang-bash">chown 1001:1002 myfile.txt
</code></pre>
<p>The command instructs the system to modify the ownership of the specified file, assigning it to a specific user and group identified by their respective numerical IDs (1001, 1002).</p>
<h2 id="heading-chgrp-change-file-group-ownership"><code>chgrp</code> – Change File Group Ownership</h2>
<p>The <code>chgrp</code> command in Red Hat Enterprise Linux (RHEL) is used to change the group ownership of files or directories. It's particularly useful when you want to modify only the group ownership without affecting the file's user owner or permissions.</p>
<h3 id="heading-syntax-of-chgrp">Syntax of <code>chgrp</code>:</h3>
<pre><code class="lang-bash">chgrp [OPTIONS] NEW_GROUP FILE...
</code></pre>
<h3 id="heading-chgrp-examples"><code>chgrp</code> examples:</h3>
<p>Change group ownership of a file:</p>
<pre><code class="lang-bash">chgrp newgroup myfile.txt
</code></pre>
<p>This changes the group ownership of a file named <code>myfile.txt</code> to a group called <code>newgroup</code>.</p>
<p>Change group ownership of a directory recursively:</p>
<pre><code class="lang-bash">chgrp -R newgroup /path/to/directory
</code></pre>
<p>This modifies the group ownership not only of the specified directory but of all its contents recursively. This ensures that everything within that directory structure is now associated with the group named <code>newgroup</code>.</p>
<p>Change group ownership and verbosely display changes:</p>
<pre><code class="lang-bash">chgrp -v newgroup myfile.txt
</code></pre>
<p>This changes the group ownership of <code>myfile.txt</code> to <code>newgroup</code> but also provides a message confirming this action. This makes the process more transparent and informs you of the change as they happen.</p>
<h2 id="heading-chmod-modify-file-permissions"><code>chmod</code> – Modify File Permissions</h2>
<p>The ability to control file permissions is a crucial aspect of Red Hat Enterprise Linux (RHEL). The <code>chmod</code> command is a powerful tool for this purpose. By utilizing this command, you can specify the accessibility levels for reading, writing, and executing a file.</p>
<h3 id="heading-syntax-of-chmod">Syntax of <code>chmod</code>:</h3>
<pre><code class="lang-bash">chmod [OPTIONS] MODE FILE...
</code></pre>
<h4 id="heading-permissions">Permissions:</h4>
<ul>
<li><p>Read (<code>r</code>): Allows reading or viewing the contents of a file.</p>
</li>
<li><p>Write (<code>w</code>): Permits modifying or deleting the file.</p>
</li>
<li><p>Execute (<code>x</code>): Grants execution permission to a file (for scripts or binaries).</p>
</li>
</ul>
<h4 id="heading-numeric-representation">Numeric representation:</h4>
<ul>
<li><p><strong>0</strong>: No permission.</p>
</li>
<li><p><strong>1</strong>: Execute.</p>
</li>
<li><p><strong>2</strong>: Write.</p>
</li>
<li><p><strong>3</strong>: Write and execute. (2+1)</p>
</li>
<li><p><strong>4</strong>: Read.</p>
</li>
<li><p><strong>5</strong>: Read and execute. (4+1)</p>
</li>
<li><p><strong>6</strong>: Read and write. (4+2)</p>
</li>
<li><p><strong>7</strong>: Read, write, and execute. (4+2+1)</p>
</li>
</ul>
<h4 id="heading-symbolic-representation">Symbolic representation:</h4>
<ul>
<li><p><code>u</code>: User/Owner.</p>
</li>
<li><p><code>g</code>: Group.</p>
</li>
<li><p><code>o</code>: Others.</p>
</li>
<li><p><code>a</code>: All (equivalent to <code>ugo</code>).</p>
</li>
</ul>
<h3 id="heading-chmod-examples"><code>chmod</code> examples:</h3>
<p>Assign read and write Permissions for owner:</p>
<pre><code class="lang-bash">chmod 600 myfile.txt
</code></pre>
<p>After executing <code>chmod 600 myfile.txt</code>, the owner of <code>myfile.txt</code> will have full read and write access to the file (the <code>6</code> in <code>**6**00</code>), while the group and others will have no permissions whatsoever (the following two 0s in <code>6**00**</code>).</p>
<p>Allow read and execute for owner, read for group, and no access for others:</p>
<pre><code class="lang-bash">chmod 540 script.sh
</code></pre>
<p>The owner of the file has both read and execute permissions (<code>5</code>). The group associated with the file has read-only access (<code>4</code>). Other users (those not in the owner group) have no permissions at all for the file (<code>0</code>).</p>
<p>Provide full permissions for all (Read, Write, Execute):</p>
<pre><code class="lang-bash">chmod 777 important_file.txt
</code></pre>
<p>The owner, the group, and all other users have complete access to read from, write to, and execute <code>important_file.txt</code>. This setting grants the broadest permissions possible, which might be risky for sensitive or important files due to unrestricted access.</p>
<p>Assign read and write permissions to the User:</p>
<pre><code class="lang-bash">chmod u+rw myfile.txt
</code></pre>
<p>The owner of <code>myfile.txt</code> (<code>u</code>) gains read and write permissions (<code>rw</code>), allowing them to both read from and write to the file.</p>
<p>Remove write permission for Others</p>
<pre><code class="lang-bash">chmod o-w myfile.txt
</code></pre>
<p>Others (users not in the owner group – <code>o</code>) lose their write permission on <code>myfile.txt</code> (<code>-w</code>). They'll be able to read the file but won't be allowed to modify it.</p>
<h2 id="heading-access-control-lists">Access Control Lists</h2>
<p>Access Control Lists (ACLs) in Red Hat Enterprise Linux (RHEL) are extensions of standard file permissions. They offer more granular control over who can access a file or directory by enabling you to set permissions for specific users or groups beyond the traditional owner, group, and others.</p>
<ul>
<li><p>Traditional permissions (read, write, execute) govern access based on owner, group, and others.</p>
</li>
<li><p>ACLs extend this by allowing permissions for multiple users and groups.</p>
</li>
</ul>
<p>In Red Hat Enterprise Linux (RHEL), <code>getfacl</code> and <code>setfacl</code> are commands used to manage Access Control Lists (ACLs) on files and directories.</p>
<h3 id="heading-access-control-list-examples">Access Control List examples:</h3>
<p>How to view ACLs:</p>
<pre><code class="lang-bash">getfacl filename
</code></pre>
<p>This retrieves and displays the ACL information for that specific file or directory. It provides a more comprehensive view of the access rights and permissions configured for that particular file in the system.</p>
<p>How to set ACLs:</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-bash">setfacl -m u:username:permissions filename
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-bash">setfacl -m u:john:rw important_file.txt
</code></pre>
<p>The code above modifies the ACL of <code>important_file.txt</code>, specifically granting read and write permissions to the user named <code>john</code>. This allows them to read from and write to the file without affecting other users' permissions.</p>
<p>Let's break down the code:</p>
<ul>
<li><p><code>setfacl</code>: The command used to set ACLs.</p>
</li>
<li><p><code>-m</code>: This option stands for "modify" and is used to modify the existing ACLs of a file or directory without altering other permissions that might already be set.</p>
</li>
<li><p><code>u:username:permissions</code>: This part specifies the user, their username, and the permissions being granted or modified for that user.</p>
</li>
<li><p><code>u</code>: Indicates that the following entry pertains to a specific user.</p>
</li>
<li><p><code>username</code>: Represents the username of the user whose permissions are being modified.</p>
</li>
<li><p><code>permissions</code>: Denotes the specific permissions being assigned to the user.</p>
</li>
</ul>
<h2 id="heading-the-umask-command">The <code>umask</code> Command</h2>
<p>In Red Hat Enterprise Linux (RHEL), <code>umask</code> stands for "user file creation mask." It's a command and a file mode creation mask that determines the default file permissions when a new file or directory is created.</p>
<p>It's represented as a three-digit octal number (for example, 022, 002, etc.).</p>
<p><strong>Calculation:</strong> The <code>umask</code> value subtracts permissions from the maximum default permissions:</p>
<ul>
<li><p>For files: Start with 666 (rw-rw-rw-) and subtract the <code>umask</code> value.</p>
</li>
<li><p>For directories: Start with 777 (rwxrwxrwx) and subtract the <code>umask</code> value.</p>
</li>
</ul>
<h3 id="heading-example-of-calculating-umask">Example of calculating <code>umask</code></h3>
<p>Let's consider an example where the umask value is <code>022</code>.</p>
<p>For files:</p>
<ul>
<li><p>Default maximum permissions: <code>666</code> (<code>rw-rw-rw-</code>)</p>
</li>
<li><p>Umask value: <code>022</code></p>
</li>
<li><p>Subtracting the umask value (<code>022</code>) from the default file permissions (<code>666</code>):</p>
</li>
<li><p>For the owner: <code>6 (rw)</code> - <code>0 (no write)</code> = <code>6 (rw-)</code></p>
</li>
<li><p>For the group: <code>6 (rw)</code> - <code>2 (no write)</code> = <code>4 (r--)</code></p>
</li>
<li><p>For others: <code>6 (rw)</code> - <code>2 (no write)</code> = <code>4 (r--)</code></p>
</li>
</ul>
<p>After applying the umask (<code>022</code>), the resulting permissions for new files becomes <code>644</code> (<code>rw-r--r--</code>).</p>
<p>For directories:</p>
<ul>
<li><p>Default maximum permissions: <code>777</code> (<code>rwxrwxrwx</code>)</p>
</li>
<li><p>Umask value: <code>022</code></p>
</li>
<li><p>Subtracting the umask value (<code>022</code>) from the default directory permissions (<code>777</code>):</p>
</li>
<li><p>For the owner: <code>7 (rwx)</code> - <code>0 (no write)</code> = <code>7 (rwx)</code></p>
</li>
<li><p>For the group: <code>7 (rwx)</code> - <code>2 (no write)</code> = <code>5 (r-x)</code></p>
</li>
<li><p>For others: <code>7 (rwx)</code> - <code>2 (no write)</code> = <code>5 (r-x)</code></p>
</li>
</ul>
<p>After applying the umask (<code>022</code>), the resulting permissions for new directories becomes <code>755</code> (<code>rwxr-xr-x</code>).</p>
<p>So with a umask value of <code>022</code>, new files will have default permissions of <code>644</code> (<code>rw-r--r--</code>) and new directories will have default permissions of <code>755</code> (<code>rwxr-xr-x</code>).</p>
<h3 id="heading-umask-examples"><code>umask</code> examples:</h3>
<p>Check the current <code>umask</code>:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">umask</span>
</code></pre>
<p>Temporarily change the <code>umask</code></p>
<pre><code class="lang-bash"><span class="hljs-built_in">umask</span> [new_umask_value]
</code></pre>
<ul>
<li><p>The first digit represents the permissions removed for the file owner.</p>
</li>
<li><p>The second digit represents the permissions removed for the group.</p>
</li>
<li><p>The third digit represents the permissions removed for others (users not in the owner group).</p>
</li>
</ul>
<p>Examples of umask values and their implications:</p>
<ul>
<li><p><code>000</code>: No permissions are removed, resulting in full read, write, and execute permissions for everyone (not recommended due to security implications).</p>
</li>
<li><p><code>022</code>: Removes write permission for others, commonly used for ensuring others can read but not modify files created by the owner.</p>
</li>
<li><p><code>077</code>: Removes all permissions for group and others, only allowing the owner full read, write, and execute permissions.</p>
</li>
<li><p><code>002</code>: Similar to <code>022</code>, but additionally allows group members to write to the files they create.</p>
</li>
</ul>
<h4 id="heading-permanent-umask-change">Permanent <code>umask</code> change</h4>
<p>If you want or need to, you can change system-wide <code>umask</code> (which is permanent). Here's how to do that:</p>
<ul>
<li><p>For system-wide changes, modify the system configuration files like <code>/etc/profile</code>, <code>/etc/bashrc</code>, or shell-specific files.</p>
</li>
<li><p>Edit the file using a text editor with administrative privileges:</p>
</li>
</ul>
<pre><code class="lang-bash"> sudo nano /etc/profile
</code></pre>
<ul>
<li><p>Locate the line setting the <code>umask</code> value and adjust it accordingly.</p>
</li>
<li><p>Save the file and exit the text editor.</p>
</li>
</ul>
<p>You can also change user-specific <code>umask</code> (also permanent). Here's how to do that:</p>
<ul>
<li>For changes specific to a user, edit their initialization file (for example, <code>~/.bashrc</code>, <code>~/.bash_profile</code>, <code>~/.profile</code>)</li>
</ul>
<pre><code class="lang-bash">vim ~/.bashrc
</code></pre>
<ul>
<li><p>Add or modify the <code>umask</code> line as needed.</p>
</li>
<li><p>Save the file and exit the text editor.</p>
</li>
</ul>
<p>To confirm the changes, type this command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">umask</span>
</code></pre>
<h2 id="heading-practical-exercises">Practical Exercises</h2>
<p>Here are some exercises to help you practice what we've covered here. Try to run through them on your own.</p>
<h3 id="heading-viewing-file-permissions">Viewing File Permissions:</h3>
<ul>
<li><p>Use the <code>ls -l</code> command to view the detailed file permissions of files in your current directory.</p>
</li>
<li><p>Interpret the output, understanding the file type, permissions, number of links, owner, group, file size, last modified time, and file/directory name.</p>
</li>
</ul>
<h3 id="heading-changing-file-ownership">Changing File Ownership:</h3>
<ul>
<li><p>Create a file named <code>example.txt</code> using any text editor (for example, <code>touch example.txt</code>).</p>
</li>
<li><p>Use the <code>ls -l</code> command to verify the ownership of <code>example.txt</code>.</p>
</li>
<li><p>Use the <code>chown</code> command to change the ownership of <code>example.txt</code> to a different user (replace <code>newowner</code> with an actual username).</p>
</li>
<li><p>Verify the ownership change using <code>ls -l</code>.</p>
</li>
</ul>
<h4 id="heading-changing-file-group-ownership">Changing File Group Ownership:</h4>
<ul>
<li><p>Create another file named <code>data.txt</code>.</p>
</li>
<li><p>Use the <code>ls -l</code> command to verify the group ownership of <code>data.txt</code>.</p>
</li>
<li><p>Use the <code>chgrp</code> command to change the group ownership of <code>data.txt</code> to a different group (replace <code>newgroup</code> with an actual group name).</p>
</li>
<li><p>Confirm the group ownership change using <code>ls -l</code>.</p>
</li>
</ul>
<h4 id="heading-modifying-file-permissions">Modifying File Permissions:</h4>
<ul>
<li><p>Create a third file named <code>script.sh</code>.</p>
</li>
<li><p>Use the <code>ls -l</code> command to view the default permissions of <code>script.sh</code>.</p>
</li>
<li><p>Use the <code>chmod</code> command to give the owner read and execute permissions, the group read permissions, and no permissions for others.</p>
</li>
<li><p>Verify the permission changes using <code>ls -l</code>.</p>
</li>
</ul>
<h4 id="heading-setting-acls">Setting ACLs:</h4>
<ul>
<li><p>Create a directory named <code>secure_folder</code>.</p>
</li>
<li><p>Use <code>getfacl</code> to view the ACLs of the directory.</p>
</li>
<li><p>Use <code>setfacl</code> to grant read and write permissions to a specific user (replace <code>john</code> with an actual username).</p>
</li>
<li><p>Verify the ACL changes using <code>getfacl</code>.</p>
</li>
</ul>
<h4 id="heading-understanding-umask">Understanding Umask:</h4>
<ul>
<li><p>Check the current umask value using the <code>umask</code> command.</p>
</li>
<li><p>Create a new file named <code>confidential.txt</code>.</p>
</li>
<li><p>Use <code>ls -l</code> to view the default permissions of <code>confidential.txt</code>.</p>
</li>
<li><p>Temporarily change the umask value to <code>027</code> using the <code>umask</code> command.</p>
</li>
<li><p>Create another file named <code>secret.txt</code> and check its default permissions.</p>
</li>
</ul>
<h4 id="heading-permanent-change-of-umask">Permanent Change of Umask:</h4>
<ul>
<li><p>For system-wide changes, modify the system configuration file (for example, <code>/etc/profile</code>, <code>/etc/bashrc</code>) to set a new default umask.</p>
</li>
<li><p>For user-specific changes, edit the user's initialization file (for example, <code>~/.bashrc</code>, <code>~/.bash_profile</code>) to set a new umask.</p>
</li>
<li><p>Verify the changes by creating a new file and checking its default permissions.</p>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thank you for exploring the world of Red Hat Enterprise Linux (RHEL) administration with me today.</p>
<p>We covered the core commands essential for precise file management in Red Hat Enterprise Linux, offering practical examples and exercises to reinforce understanding and proficiency.</p>
<p>You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manage Users and Groups in Red Hat Enterprise Linux ]]>
                </title>
                <description>
                    <![CDATA[ To effectively safeguard your system and regulate access when working in Red Hat Enterprise Linux (RHEL), you'll need to understand user and group management. This is a critical component that's significant for both individual and complex network env... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/manage-users-and-groups-in-rhel/</link>
                <guid isPermaLink="false">66d45f6d264384a65d5a955a</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Mon, 08 Jan 2024 17:41:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/manage-users-and-groups-in-rhel-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>To effectively safeguard your system and regulate access when working in Red Hat Enterprise Linux (RHEL), you'll need to understand user and group management.</p>
<p>This is a critical component that's significant for both individual and complex network environments, as it's key to adeptly handle user accounts and groups.</p>
<p>In this guide, we'll dive into the fundamentals of user and group management within RHEL. You'll gain the knowledge and skills necessary to confidently create, modify, and optimize user accounts and groups, according to your specific security and operational needs.</p>
<p>You'll also learn the ins and outs of granting user permissions and implementing group-based access controls, and master the essential tools and proven methods for ensuring robust system integrity and regulating resource access.</p>
<h2 id="heading-prerequisite">Prerequisite</h2>
<ul>
<li>Familiarity with basic Linux commands. You can read my previous <a target="_blank" href="https://www.freecodecamp.org/news/red-hat-enterprise-linux-guide/">tutorial on RHEL commands and key concepts</a> if you need to brush up.</li>
</ul>
<h2 id="heading-table-of-contents"><strong>Table Of Contents</strong></h2>
<p>Here's what we'll cover in this comprehensive guide:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-useradd-command">useradd</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-sudo">What is sudo?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-usermod-command">usermod</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-etclogindefs">What is /etc/login.defs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-etcskel">What is /etc/skel?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-etcshadow">What is /etc/shadow?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-groupadd-command">groupadd</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-groupmod-command">groupmod</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-exercise">Practical Exercise</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-the-useradd-command">The <code>useradd</code> Command</h2>
<p>The <code>useradd</code> command is an essential tool in RHEL for creating new user accounts. This command not only adds the user's information to the system files, but also sets up their home directory and default configurations.</p>
<h3 id="heading-syntax-of-the-useradd-command">Syntax of the <code>useradd</code> command:</h3>
<pre><code class="lang-bash">useradd [options] username
</code></pre>
<h2 id="heading-what-is-sudo">What is sudo?</h2>
<p>In the world of Linux/Unix, <code>sudo</code> stands for "Superuser Do." Essentially, it's a command that grants regular users the ability to run commands with full administrative or root permissions. This is especially useful for commands that may be restricted for regular users due to security reasons.</p>
<h3 id="heading-examples">Examples:</h3>
<p>Just a quick reminder – if you're not currently logged in as the root user, be sure to utilize <code>sudo</code> before using commands such as <code>useradd</code> that we'll be discussing in this tutorial. Consider <code>sudo</code> as a handy tool that grants you some of the root user's abilities. We'll go more in-depth on this topic in future tutorials.</p>
<p>At the moment, I am logged in as a root user. So I won't be using <code>sudo</code> before any commands.</p>
<h4 id="heading-create-a-user">Create a user:</h4>
<pre><code class="lang-bash">useradd kedar
</code></pre>
<p>This command makes a new user called 'kedar' and sets up a home folder for them by default. Later on, we'll learn more about <code>useradd</code> and how we can change these defaults.</p>
<p>In RHEL, some values are already set when creating a user, but we'll explore them further in this tutorial.</p>
<h4 id="heading-check-a-newly-added-user">Check a newly added user:</h4>
<pre><code class="lang-bash">tail -1 /etc/passwd
</code></pre>
<p><code>/etc/passwd</code> serves as a centralized repository containing essential information about user accounts. The output of the above command will be displayed in following way:</p>
<pre><code class="lang-bash">kedar:x:1001:1001:John Doe:/home/john:/bin/bash
</code></pre>
<p>If the user was added successfully, you will see the above output. Now there may be some changes, but it should look essentially the same.</p>
<p>Let's break this output down and try to understand it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Frame-1000004542.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Breakdown of the above output</em></p>
<ol>
<li><p>Username – the name of the user account.</p>
</li>
<li><p>Password Placeholder (Obsolete) – historically, this field contained an 'x' character, indicating that the encrypted password for the user was stored in the <code>/etc/shadow</code> file.</p>
</li>
<li><p>User ID (UID) – unique numerical identifier assigned to the user.</p>
</li>
<li><p>Group ID (GID) – the numerical identifier of the primary group associated with the user.</p>
</li>
<li><p>User Information (GECOS) – this field usually includes additional information like the user's full name, contact details, and so on.</p>
</li>
<li><p>Home Directory – the path to the user's home directory.</p>
</li>
<li><p>Login Shell – the default shell or program executed upon login for the user.</p>
</li>
</ol>
<p>Once the user is created, we can set password for that user. This can be only done from a root account.</p>
<h4 id="heading-set-a-password-for-a-newly-created-account">Set a password for a newly created account</h4>
<pre><code class="lang-bash">passwd kedar
</code></pre>
<p>This will ask you to type password for the kedar user. Once the password is set you can login to kedar user using the GUI. Setting password is important if you want to login through the GUI.</p>
<h4 id="heading-set-different-options-for-the-user-while-creating-a-new-user">Set different options for the user while creating a new user</h4>
<p>Now that we know what options are available while creating a user, we can set them according to our needs.</p>
<ol>
<li>User Id (<code>-u</code>)</li>
</ol>
<pre><code class="lang-bash">useradd -u 1234 kedar
</code></pre>
<p>Above command with the <code>-u</code> option will set User Id to 1234 while creating the user kedar.</p>
<ol start="2">
<li>Primary Group (<code>-g</code>)</li>
</ol>
<pre><code class="lang-bash">useradd -g 1232 kedar
</code></pre>
<p>If there is an existing group and you know the group Id or group Name, you can add that group as a primary group for the kedar user.</p>
<ol start="3">
<li>Secondary Group (<code>-G</code>)</li>
</ol>
<pre><code class="lang-bash">useradd -G developers kedar
</code></pre>
<p>User kedar will be added to a secondary group called developers which already exists. We can add the user to multiple secondary groups.</p>
<p>Think of a secondary group in Linux as a coveted club membership for users. While they are automatically included in a primary group when working on the computer, joining secondary groups allows users to expand their membership and gain access to additional files and features.</p>
<p>Essentially, it's like being a part of multiple groups simultaneously, providing users with additional privileges and the ability to explore different parts of the system.</p>
<ol start="4">
<li>User Information</li>
</ol>
<pre><code class="lang-bash">useradd -c <span class="hljs-string">"2 Month Intern"</span> kedar
</code></pre>
<p>This adds more information to user kedar as "2 Month Intern". This will be displayed in the <code>/etc/passwd</code> file.</p>
<ol start="5">
<li>Home Directory</li>
</ol>
<pre><code class="lang-bash">useradd -d /etc/kedar/home kedar
</code></pre>
<p>Now this will set the home directory to <code>/etc/kedar/home</code> for the kedar user. By default in RHEL, the home directory, if not specified, is <code>/home/kedar</code>.</p>
<ol start="6">
<li>Login Shell</li>
</ol>
<pre><code class="lang-bash">useradd -s /bin/shell kedar
</code></pre>
<p>Here, the kedar user will have access to the shell which is in /bin/shell. This will give access to the shell to the user kedar.</p>
<p>The /bin/bash access pertains to a user's default shell upon logging into the system.</p>
<p>In the Linux world, the /bin/bash shell is commonly known as the Bash shell, short for "Bourne Again SHell," and is readily available on most Linux distributions. When a user is granted /bin/bash access, it means that upon login, they will be greeted with the Bash shell's command-line interface.</p>
<p>This powerful shell equips them with the ability to interact with the system, run commands, and execute Bash-specific scripts using its unique syntax and functionality.</p>
<p>Given its widespread usage, advanced capabilities, and compatibility with a variety of scripting languages and command-line tasks, the /bin/bash shell is a preferred option for many users as their default shell.</p>
<p>If you want to remove shell access from a particular user, you can set shell access like this: <code>/sbin/nologin</code>. This will restrict access to this user to logging into their account until shell access is set to <code>/bin/shell</code>.</p>
<pre><code class="lang-bash">useradd -s /sbin/nologin kedar
</code></pre>
<h2 id="heading-the-usermod-command">The <code>usermod</code> Command</h2>
<p>The usermod command is super important in Linux. It helps admins easily change things about user accounts after they're made. This saves time because you don't have to delete and make the accounts again. It's a handy way to manage users without much hassle.</p>
<h3 id="heading-syntax-of-the-usermod-command">Syntax of the <code>usermod</code> command:</h3>
<pre><code class="lang-bash">usermod [options] username
</code></pre>
<h3 id="heading-examples-1">Examples:</h3>
<h4 id="heading-change-username">Change username:</h4>
<pre><code class="lang-bash">usermod -l newusername oldusername
</code></pre>
<p>This command changes the username from <code>oldusername</code> to <code>newusername</code>.</p>
<h4 id="heading-change-user-id-uid">Change User ID (UID):</h4>
<pre><code class="lang-bash">usermod -u &lt;newUID&gt; username
</code></pre>
<p>This command replaces <code>&lt;newUID&gt;</code> with the desired new UID for the user.</p>
<h4 id="heading-change-group-id-gid">Change Group ID (GID):</h4>
<pre><code class="lang-bash">usermod -g &lt;newGID&gt; username
</code></pre>
<p>This command replaces <code>&lt;newGID&gt;</code> with the desired new primary group ID for the user.</p>
<h4 id="heading-add-user-to-supplementary-groups">Add user to supplementary groups:</h4>
<pre><code class="lang-bash">usermod -aG group1,group2 username
</code></pre>
<p>This command adds the user to additional supplementary groups (<code>group1</code>, <code>group2</code>, etc.).</p>
<h4 id="heading-change-home-directory">Change home directory:</h4>
<pre><code class="lang-bash">usermod -d /newhome username
</code></pre>
<p>This command changes the user's home directory to <code>/newhome</code>.</p>
<h4 id="heading-change-default-shell">Change default shell:</h4>
<pre><code class="lang-bash">usermod -s /bin/bash username
</code></pre>
<p>This command changes the default shell for the user to <code>/bin/bash</code>.</p>
<h4 id="heading-set-expiry-date-for-account">Set expiry date for account:</h4>
<pre><code class="lang-bash">usermod -e YYYY-MM-DD username
</code></pre>
<p>This command sets an expiration date (<code>YYYY-MM-DD</code>) for the user's account.</p>
<p>You can explore more about this command using <code>man usermod</code>. You have the same options as with <code>useradd</code> to manipulate the information of a user when you use the <code>usermod</code> command.</p>
<h2 id="heading-what-is-etclogindefs">What is <code>/etc/login.defs</code>?</h2>
<p>The <code>/etc/login.defs</code> file is a crucial configuration file that sets default parameters for login, password policies, and user account creation. It can be found at the usual location, /etc/login.defs, and plays a key role in determining system-wide defaults for user management and authentication.</p>
<p>There is also a fixed range for user UIDs, as shown in the following table:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Frame-1000004563-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>UID range table - Privileged users: 0-99, System users: 201-999, Normal users: 1000-60000</em></p>
<p>The directory /etc/login.defs contains a variety of default configurations. By accessing this directory, we can modify these settings to our liking.</p>
<p>This file contains several different options that we can adjust, some of which are listed below:</p>
<pre><code class="lang-bash">PASS_MAX_DAYS   90
PASS_MIN_DAYS   7
PASS_WARN_AGE   14
PASS_MIN_LEN    8

UID_MIN         1000
UID_MAX         60000
GID_MIN         1000
GID_MAX         60000

LOGIN_RETRIES   5
LOGIN_TIMEOUT   60
CREATE_HOME     yes
UMASK           077

ENCRYPT_METHOD  SHA512
CHFN_AUTH       yes
CHFN_RESTRICT   rwh
DEFAULT_HOME    /home
</code></pre>
<p>Now you know where the default settings come from when we create a user. You can change these settings according to your needs.</p>
<h2 id="heading-what-is-etcskel">What is <code>/etc/skel</code>?</h2>
<p>In Linux and similar systems, the <code>/etc/skel/</code> folder is like a starter pack for new users. It's called "skel" short for "skeleton" because it sets up the basics for new users.</p>
<p>This folder contains a set of files and folders that are copied into a new user's home folder. Whenever a new user is made, these essential files from /etc/skel/ are automatically put into their home folder, making sure it has what they need to get started.</p>
<p>This helps set up a simple starting point for the user. It gives them basic configurations, default settings, and sometimes example files. This method ensures that every new user starts with a standard setup and the required files.</p>
<p>In the /etc/skel/ folder, you might find common files like .bashrc, .profile, and similar configuration files.</p>
<h2 id="heading-what-is-etcshadow">What is <code>/etc/shadow</code>?</h2>
<p>The <code>/etc/shadow</code> file is a crucial component of Unix-based operating systems (like Linux), as it serves as a repository for encrypted user passwords and other password-related data. This enhanced security measure surpasses previous methods of storing passwords in the /etc/passwd file.</p>
<p>The /etc/shadow file contains crucial information pertaining to user account passwords. Each line in the file represents a particular user and is divided into multiple fields, each separated by a colon (:).</p>
<p>These fields typically include the username, the encrypted password (hashed using a cryptographic algorithm, not the actual password), the number of days since the last password change (starting from January 1, 1970), information about password expiry such as minimum and maximum age, and a warning period. It also specifies the number of days of inactivity allowed before the account is locked, and if the account has an expiration date.</p>
<h3 id="heading-sample-entry-of-etcshadow-file">Sample entry of /etc/shadow file</h3>
<p><code>user:$6$PswrdHash$E7KLkQIGo7mxG5vDi7JelC5D8L0qbg38z1/WgNhAZDpCoe2GyGB6JefT9ftb/Rfm3uZOlFkktj/SkJTfSJziO.:18830:0:90:7:::</code></p>
<p>Where:</p>
<ul>
<li><p><code>user</code>: Username</p>
</li>
<li><p><code>$6$PswrdHash$E7KLkQIG...</code>: Encrypted password hash</p>
</li>
</ul>
<ol>
<li><p><strong>$1$</strong> is MD5</p>
</li>
<li><p><strong>$2a$</strong> is Blowfish</p>
</li>
<li><p><strong>$2y$</strong> is Blowfish</p>
</li>
<li><p><strong>$5$</strong> is SHA-256</p>
</li>
<li><p><strong>$6$</strong> is SHA-512</p>
</li>
<li><p><strong>$y$</strong> is yescrypt</p>
</li>
</ol>
<p>These symbols help identify the hashing algorithm used for each password hash stored in the <code>/etc/shadow</code> file. For instance, if you see a password hash starting with <code>$6$</code>, it indicates that SHA-512 encryption has been used for that particular password.</p>
<ul>
<li><p><code>18830</code>: Last password change date (days since Jan 1, 1970)</p>
</li>
<li><p><code>0</code>: Minimum password age</p>
</li>
<li><p><code>90</code>: Maximum password age</p>
</li>
<li><p><code>7</code>: Password warning period</p>
</li>
<li><p>Other fields for account inactivity and expiration</p>
</li>
</ul>
<p>Access: In order to access and modify the <code>/etc/shadow</code> file, you must have root user permissions or specialized privileges granted.</p>
<p>Modification: For enhanced security, it is advised to use designated commands such as <code>passwd</code>, which handles password encryption and updates the /etc/shadow file effectively.</p>
<h2 id="heading-the-groupadd-command">The <code>groupadd</code> Command</h2>
<p>In RHEL, you use the <code>groupadd</code> command to create new groups on the system. It's a fundamental command for managing user groups, allowing system administrators to add groups, set their properties, and define their membership.</p>
<p>All default settings for groups are in <code>/etc/login.defs</code>. The /etc/login.defs file contains important settings, such as GID_MIN, which determines the minimum GID value for regular groups, and GID_MAX, which sets the maximum GID value. Additionally, SYS_GID_MIN and SYS_GID_MAX determine the minimum and maximum GID values for system groups.</p>
<p>These settings play a crucial role in the management of groups within the system.</p>
<h3 id="heading-syntax-of-the-groupadd-command">Syntax of the <code>groupadd</code> command:</h3>
<pre><code class="lang-bash">groupadd [options] groupname
</code></pre>
<h3 id="heading-examples-2">Examples:</h3>
<h4 id="heading-creating-a-group">Creating a group:</h4>
<pre><code class="lang-bash">groupadd developers
</code></pre>
<p>The above command create a new group named "developers".</p>
<h4 id="heading-assigning-a-specific-gid">Assigning a specific GID:</h4>
<pre><code class="lang-bash">groupadd -g 1001 developers
</code></pre>
<p>This command creates a group with a specified GID (for example, GID 1001).</p>
<p>You can explore more options according to your needs using the <code>man groupadd</code> command. This will give you documentation of the <code>groupadd</code> command.</p>
<h2 id="heading-the-groupmod-command">The <code>groupmod</code> Command</h2>
<p>The <code>groupmod</code> command in RHEL is a valuable tool for system administrators, as it enables them to effortlessly modify existing group attributes.</p>
<p>With this powerful command, you can alter groups without the need for recreating them, making it a crucial asset for system maintenance.</p>
<h3 id="heading-syntax-of-the-groupmod-command">Syntax of the <code>groupmod</code> command:</h3>
<pre><code class="lang-bash">groupmod [options] groupname
</code></pre>
<h3 id="heading-examples-3">Examples:</h3>
<h4 id="heading-change-group-name">Change group name:</h4>
<pre><code class="lang-bash">groupmod -n newgroupname oldgroupname
</code></pre>
<p>This command changes the group name from <code>oldgroupname</code> to <code>newgroupname</code>.</p>
<h4 id="heading-change-gid-group-id">Change GID (Group ID):</h4>
<pre><code class="lang-bash">groupmod -g &lt;newGID&gt; groupname
</code></pre>
<p>This command changes the group's GID to <code>&lt;newGID&gt;</code>.</p>
<h4 id="heading-add-group-to-supplementary-groups">Add group to supplementary groups:</h4>
<pre><code class="lang-bash">groupmod -aG group1,group2 groupname
</code></pre>
<p>This command adds the group to additional supplementary groups (<code>group1</code>, <code>group2</code>, and so on).</p>
<h4 id="heading-add-users-from-a-group">Add users from a group:</h4>
<pre><code class="lang-bash">groupmod -m -m user1,user2 developers
</code></pre>
<p>This will add user1 and user2 to the developers group.</p>
<h4 id="heading-remove-users-from-a-group">Remove users from a group:</h4>
<pre><code class="lang-bash">groupmod -M user1,user2 developers
</code></pre>
<p>This will remove user1 and user2 from the developers group.</p>
<p>You can explore more options according to your needs using the <code>man groupmod</code> command. This will give you documentation of the <code>groupmod</code> command.</p>
<h2 id="heading-practical-exercise">Practical Exercise</h2>
<h3 id="heading-exercise-1-basic-user-and-group-management">Exercise 1: Basic User and Group Management</h3>
<ol>
<li><strong>Creating Users and Groups</strong></li>
</ol>
<ul>
<li><p>Use <code>useradd</code> to create a new user named "testuser."</p>
</li>
<li><p>Use <code>groupadd</code> to create a group named "testgroup."</p>
</li>
<li><p>Ensure the user "testuser" is part of the group "testgroup."</p>
</li>
</ul>
<h3 id="heading-exercise-2-user-modifications">Exercise 2: User Modifications</h3>
<ol>
<li><strong>Modifying User Attributes</strong></li>
</ol>
<ul>
<li><p>Use <code>usermod</code> to change the default shell for "testuser" to <code>/bin/bash</code>.</p>
</li>
<li><p>Modify the user's login name from "testuser" to "newuser" using <code>usermod</code>.</p>
</li>
<li><p>Confirm the changes by checking <code>/etc/passwd</code>.</p>
</li>
</ul>
<h3 id="heading-exercise-3-group-modifications">Exercise 3: Group Modifications</h3>
<ol>
<li><strong>Group Modifications</strong></li>
</ol>
<ul>
<li><p>Use <code>groupmod</code> to rename "testgroup" to "newgroup."</p>
</li>
<li><p>Change the GID (Group ID) of "newgroup" using <code>groupmod</code>.</p>
</li>
<li><p>Add "newuser" to the "newgroup" using <code>usermod</code>.</p>
</li>
</ul>
<h3 id="heading-exercise-4-advanced-user-and-group-management">Exercise 4: Advanced User and Group Management</h3>
<ol>
<li><strong>Setting User and Group Limits</strong></li>
</ol>
<ul>
<li><p>Set password policies using parameters in <code>/etc/login.defs</code>.</p>
</li>
<li><p>Configure group default settings like GID_MIN and GID_MAX in <code>/etc/login.defs</code>.</p>
</li>
</ul>
<h3 id="heading-exercise-5-understanding-etcshadow-and-etcskel">Exercise 5: Understanding <code>/etc/shadow</code> and <code>/etc/skel</code></h3>
<ol>
<li><strong>Exploring Password Storage and Defaults</strong></li>
</ol>
<ul>
<li><p>Examine the <code>/etc/shadow</code> file to understand the password storage format.</p>
</li>
<li><p>Create a new user and observe their entry in <code>/etc/shadow</code>.</p>
</li>
<li><p>Explore <code>/etc/skel</code> and understand its purpose by creating a new user and observing their home directory.</p>
</li>
</ul>
<h3 id="heading-exercise-6-challenge">Exercise 6: Challenge</h3>
<ol>
<li><strong>Managing Permissions and Access Control</strong></li>
</ol>
<ul>
<li><p>Set up directory permissions so that only "newuser" in "newgroup" can read/write to a specific folder.</p>
</li>
<li><p>Experiment with <code>chown</code> and <code>chmod</code> commands to change ownership and permissions.</p>
</li>
</ul>
<h3 id="heading-exercise-7-real-world-scenario">Exercise 7: Real-world Scenario</h3>
<ol>
<li><strong>Creating Users with Specific Configurations</strong></li>
</ol>
<ul>
<li><p>Create a user named "admin" with a customized home directory (/opt/admin) and a specific default shell.</p>
</li>
<li><p>Set a password policy that applies only to the "admin" user.</p>
</li>
</ul>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>Thank you for exploring how to manage users and groups in RHEL with me today. You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Red Hat Enterprise Linux – Essential RHEL Concepts and Commands to Know ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to the fundamental world of Red Hat Enterprise Linux (RHEL)! In order to be an effective Linux user, you'll need to learn and truly understand some essential concepts and commands. Let's dive into the core aspects of RHEL administration to he... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/red-hat-enterprise-linux-guide/</link>
                <guid isPermaLink="false">66d45f72264384a65d5a956a</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Wed, 03 Jan 2024 15:54:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/red-hat-enterprise-linux-guide-cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to the fundamental world of Red Hat Enterprise Linux (RHEL)! In order to be an effective Linux user, you'll need to learn and truly understand some essential concepts and commands.</p>
<p>Let's dive into the core aspects of RHEL administration to help you understand these key topics that form the backbone of day-to-day operations. The only prerequisites are a desire to learn Linux and a willingness to code along at home and complete the exercises at the end.</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<p>Here's what we'll cover in this comprehensive guide:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-rhel">What is RHEL?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-no-need-to-set-up-linux-locally">No Need to Set Up Linux Locally</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-upstream-amp-downstream">Understanding Upstream &amp; Downstream</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-essential-rhel-command-line-tools-and-functions">Essential RHEL Command Line Tools and Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-the-linux-file-system-works">How the Linux File System Works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-text-editors">Text Editors</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-exercises">Practical Exercises</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-what-is-rhel">What is RHEL?</h2>
<p>RHEL is a popular member of the Linux distribution family. It stands out for its strong reliability, stability, and security capabilities.</p>
<p>Created by Red Hat, RHEL is specifically designed for enterprise usage, striking a helpful balance between innovative technologies and a commitment to dependability, extensive support, and seamless compatibility.</p>
<p>RHEL is a solid choice for businesses, organizations, and developers seeking a reliable operating system for high-priority tasks. It offers a robust base for server setups, data centers, cloud computing, and business applications, and is often a go-to option for mission-critical workloads.</p>
<h2 id="heading-no-need-to-set-up-linux-locally">No Need to Set Up Linux Locally</h2>
<p>You don't need to set up Linux on your system to follow this guide. Instead, you can practice whatever you learn here on an interactive online platform.</p>
<p>You can visit <a target="_blank" href="https://killercoda.com/playgrounds/scenario/ubuntu">this website</a> to access a Linux playground where you can execute commands and explore Linux without installation.</p>
<h2 id="heading-understanding-upstream-amp-downstream">Understanding Upstream &amp; Downstream</h2>
<h3 id="heading-upstream">Upstream</h3>
<p>Upstream represents the original or source software from which derivatives or distributions are derived. For Red Hat Enterprise Linux (RHEL), Fedora serves as its primary source for updates and features.</p>
<p>RHEL integrates developments from Fedora's open-source platform into its enterprise-level distribution. Changes initiated within Fedora are systematically integrated into RHEL as part of its upstream progression.</p>
<p>Software upstream commonly includes the latest, experimental features and developments driven by the community. It forms the base for related projects, functioning as a testing area for trying out new functions</p>
<h3 id="heading-downstream">Downstream</h3>
<p>Downstream refers to distributions or versions derived from the upstream source. These distributions typically incorporate modifications, adjustments, and additional features tailored to specific needs.</p>
<p>CentOS, a widely-used version that comes after RHEL, uses RHEL's code but without its branding and exclusive parts, providing a no-cost alternative.</p>
<p>Likewise, distributions such as Oracle Linux are also built from RHEL's codebase, but they make their changes and packaging adjustments.</p>
<p>Downstream serve different groups of users by taking the main features from the original source and tweaking them to fit specific needs, like stability, support, or particular uses.</p>
<h2 id="heading-essential-rhel-command-line-tools-and-functions">Essential RHEL Command Line Tools and Functions</h2>
<p>By learning the fundamental commands I outline below, you can navigate and manage your Linux environment with ease. These commands act as the foundation for a deeper understanding of Linux systems, and they'll empower you to expand your expertise and knowledge further.</p>
<h3 id="heading-echo"><code>echo</code></h3>
<p>The <code>echo</code> command is used to show text or variables as output. It's a straightforward yet robust tool often used in scripting and working with command-line interfaces.</p>
<h5 id="heading-syntax">Syntax:</h5>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> [OPTIONS] [STRING]
</code></pre>
<h5 id="heading-examples">Examples:</h5>
<p>Displaying text:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, World!"</span>
</code></pre>
<p>This will print given text as it is on a user's screen.</p>
<p>Displaying variables:</p>
<pre><code class="lang-bash">name=<span class="hljs-string">"John"</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$name</span>"</span>
</code></pre>
<p>We can directly declare a variable and assign a value to that variable. We can use <code>$</code> in front of the variable name to print it using the <code>echo</code> command.</p>
<p>Escape Sequences:</p>
<p>Escape sequences are combinations of characters that are used to represent certain special characters or actions within strings. These sequences typically start with a backslash <code>\</code> followed by a specific character or sequence of characters.</p>
<p>When the compiler or interpreter encounters an escape sequence within a string, it interprets it as a special instruction rather than a literal character.</p>
<ul>
<li><p><code>\n</code>: Represents a newline character. When this sequence is encountered within a string, it signifies a line break.</p>
</li>
<li><p><code>\t</code>: Represents a tab character. It's used to create horizontal tabs or spaces within a string.</p>
</li>
<li><p><code>\</code>: Represents a single backslash character. Since the backslash is an escape character itself, using <code>\</code> allows you to include a literal backslash in a string.</p>
</li>
<li><p><code>\"</code> : Represents a double quote or a single quote character respectively within a string. These are useful when you want to include quotes within a string that is itself enclosed in quotes.</p>
</li>
</ul>
<p>We need to use the <code>-e</code> option along with the <code>echo</code> command to enable escape sequences. <code>-e</code> enables the interpretation of backslash escapes.</p>
<h5 id="heading-examples-1">Examples:</h5>
<p>Printing a new sentence on a new line:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> -e <span class="hljs-string">"This is a new line.\nThis is another line."</span>
</code></pre>
<p>Now both lines will be on a separate line rather than continuing one after another. You can try using other options from above.</p>
<h3 id="heading-whoami"><code>whoami</code></h3>
<p>whoami is used to display the username of the current user who is logged in to the system.</p>
<h5 id="heading-example">Example</h5>
<pre><code class="lang-bash">whoami
</code></pre>
<p>Running <code>whoami</code> in a terminal will output the username of the current user. For instance, if you're logged in as "Kedar," it will display <code>Kedar</code>. It serves a specific purpose of showing the current user's identity and doesn't have additional options or variations.</p>
<h3 id="heading-cat"><code>cat</code></h3>
<p>The cat command is used primarily to read, create, concatenate, and display the content of files. Its name is derived from "concatenate," which means to link things together.</p>
<h5 id="heading-syntax-1">Syntax:</h5>
<pre><code class="lang-bash">cat [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-examples-2">Examples:</h5>
<p>Displaying file content:</p>
<pre><code class="lang-bash">cat filename.txt
</code></pre>
<p>This will display the contents of filename.txt in the terminal.</p>
<p>Concatenating multiple files:</p>
<pre><code class="lang-bash">cat file1.txt file2.txt &gt; combined.txt
</code></pre>
<p>This code concatenates file1.txt and file2.txt and redirects their content to combined.txt.</p>
<p>Creating or appending to a file:</p>
<p>The output of <code>cat</code> can be redirected using <code>&gt;</code> (create/overwrite) or <code>&gt;&gt;</code> (append) to store the content into a file.</p>
<p>To create a new file and add content to it, try this command:</p>
<pre><code class="lang-bash">cat &gt; newfile.txt
</code></pre>
<p>This will allow you to type content into the terminal, and pressing Ctrl + D will save it to newfile.txt.</p>
<p>To append content to an existing file, try this:</p>
<pre><code class="lang-bash">cat &gt;&gt; existingfile.txt
</code></pre>
<p>Similar to the previous command, this allows you to add content to existingfile.txt.</p>
<p>Display line numbers along with the content:</p>
<p>We can show line number along with content using <code>-n</code> option with cat.</p>
<pre><code class="lang-bash">cat -n filename.txt
</code></pre>
<p>Display a dollar sign ($) at the end of each line:</p>
<p>We can show a <code>$</code> at end of each line along with content using the <code>-E</code> option with <code>cat</code> like this:</p>
<pre><code class="lang-bash">cat -E filename.txt
</code></pre>
<h3 id="heading-touch"><code>touch</code></h3>
<p>The touch command is used to create new, empty files or update the timestamps of existing files without changing their content.</p>
<h5 id="heading-syntax-2">Syntax:</h5>
<pre><code class="lang-bash">touch [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-examples-3">Examples:</h5>
<p>Creating a new file:</p>
<pre><code class="lang-bash">touch newfile.txt
</code></pre>
<p>This command creates a new file named newfile.txt. If the file already exists, it updates the timestamp to the current time.</p>
<p>Creating multiple files:</p>
<pre><code class="lang-bash">touch file1.txt file2.txt file3.txt
</code></pre>
<p>This creates multiple files (file1.txt, file2.txt, file3.txt) simultaneously.</p>
<p>Also, we can create files with changing numbers or letters dynamically. We need to give the range of letters or numbers in curly braces:</p>
<pre><code class="lang-bash">touch file{1..3}.txt
</code></pre>
<p>This will create <code>file1.txt</code>, <code>file2.txt</code> and <code>file3.txt</code>.</p>
<h3 id="heading-ls"><code>ls</code></h3>
<p>The <code>ls</code> command is used to list files and directories in a specified location.</p>
<h5 id="heading-syntax-3">Syntax:</h5>
<pre><code class="lang-bash">ls [OPTIONS] [DIRECTORY/PATH_OF_DIRECTORY]
</code></pre>
<h5 id="heading-examples-4">Examples:</h5>
<p>List files in the current directory:</p>
<pre><code class="lang-bash">ls
</code></pre>
<p>This command lists all files and directories in the current working directory.</p>
<p>List files in a specific directory:</p>
<pre><code class="lang-bash">ls /custom/path
</code></pre>
<p>Replace /custom/path with the actual path to list files and directories in that specific directory.</p>
<p>List hidden files:</p>
<pre><code class="lang-bash">ls -a
ls -a /custom/path
</code></pre>
<p>The <code>-a</code> option shows all files, including hidden ones (those starting with a dot, for example .hiddenfile).</p>
<p>List all details of directory/files:</p>
<pre><code class="lang-bash">ls -l /custom/path
</code></pre>
<p>This provides a detailed, long listing format that gives more information about directories and files. You will learn more about the details which <code>ls -l</code> provides in an upcoming article.</p>
<p>Display Directory/File size:</p>
<pre><code class="lang-bash">ls -h /custom/path
</code></pre>
<p>Displays file sizes in a human-readable format (e.g., kilobytes, megabytes).</p>
<p>Show modified files first:</p>
<pre><code class="lang-bash">ls -t /custom/path
</code></pre>
<p>This command sorts files by modification time, showing the newest files first.</p>
<p>We can also use these options together like this:</p>
<pre><code class="lang-bash">ls -la /custom/path
</code></pre>
<p>This will list all files and directory along with hidden files (-a) and details information of files and directories (-l).</p>
<h3 id="heading-date"><code>date</code></h3>
<p>The date command is used to display or set the system date and time.</p>
<h5 id="heading-syntax-4">Syntax:</h5>
<pre><code class="lang-bash">date [OPTIONS]
</code></pre>
<h5 id="heading-examples-5">Examples:</h5>
<p>Displaying the current date and time:</p>
<pre><code class="lang-bash">date
</code></pre>
<p>This will display the current date and time of your system.</p>
<p>Setting the date and time:</p>
<pre><code class="lang-bash">date MMDDhhmm[[CC]YY][.ss]
</code></pre>
<ul>
<li><p>MM: Month (01-12)</p>
</li>
<li><p>DD: Day (01-31)</p>
</li>
<li><p>hh: Hour (00-23)</p>
</li>
<li><p>mm: Minute (00-59)</p>
</li>
<li><p>CC: Century (optional, for years earlier than 2000)</p>
</li>
<li><p>YY: Year (optional, 00-99)</p>
</li>
<li><p>.ss: Seconds (optional, 00-61)</p>
</li>
</ul>
<p>This command will let you set whatever date and time you want on your system.</p>
<p>Customizing date output:</p>
<pre><code class="lang-bash">date +<span class="hljs-string">"%A, %B %d, %Y"</span>
</code></pre>
<p>Options</p>
<ul>
<li><p>%A = Full weekday name (for example, Sunday)</p>
</li>
<li><p>%B = full month name (for example, January)</p>
</li>
<li><p>%d = day of month (for example, 01)</p>
</li>
<li><p>%Y = year</p>
</li>
</ul>
<p>This will display <code>Saturday, December 16, 2023</code>. You can find more options for date using the <code>man date</code> command.</p>
<p><strong>Note</strong>: If you want to find in-depth information about any command, use <code>man your_command</code> to get more information.</p>
<h3 id="heading-cal"><code>cal</code></h3>
<p>The <code>cal</code> command is used to display a calendar for a specified month or year.</p>
<h5 id="heading-syntax-5">Syntax:</h5>
<pre><code class="lang-bash">cal [OPTIONS] [MONTH] [YEAR]
</code></pre>
<h5 id="heading-examples-6">Examples:</h5>
<p>Displaying the current month's calendar:</p>
<pre><code class="lang-bash">cal
</code></pre>
<p>This command displays the calendar for the current month.</p>
<p>Displaying a specific month and year:</p>
<pre><code class="lang-bash">cal 12 2023
</code></pre>
<p>This command displays the calendar for December 2023.</p>
<p>Displaying a specific year:</p>
<pre><code class="lang-bash">cal 2023
</code></pre>
<p>Displaying Julian days:</p>
<p>"Julian days" refers to a simple way of counting days. Instead of using dates like January 1st or February 15th, Julian days just count the number of days that have passed since a specific starting point. This starting point is called the Julian Day Number (JDN), which began on January 1st, 4713 BC in the Julian calendar.</p>
<p>For example, January 1st, 4713 BC is Julian day 0. Each day after that is counted as Julian day 1, 2, 3, and so on. It's like a continuous count of days without worrying about months or years. It's a handy way for scientists, astronomers, and other professionals to keep track of time because it's a straightforward system of counting days.</p>
<pre><code class="lang-bash">cal -j 12 2023
</code></pre>
<p>This command displays the calendar for December 2023 along with the corresponding Julian days.</p>
<h3 id="heading-mkdir"><code>mkdir</code></h3>
<p>You use this command to create new directories, organizing the file system structure efficiently. <code>mkdir</code> stands for <code>Make Directory</code>.</p>
<h5 id="heading-syntax-6">Syntax:</h5>
<pre><code class="lang-bash">mkdir [OPTIONS] DIRECTORY_NAME(s)
</code></pre>
<h5 id="heading-examples-7">Examples:</h5>
<p>Creating a single directory:</p>
<pre><code class="lang-bash">mkdir new_directory
</code></pre>
<p>This command creates a new directory named new_directory in the current working directory.</p>
<p>Creating multiple directories:</p>
<pre><code class="lang-bash">mkdir dir1 dir2 dir3
</code></pre>
<p>This command creates multiple directories named dir1, dir2, and dir3 in the current working directory.</p>
<p>We can also make this command little bit more intresting. We can create n numbers of directories if you want them in a sequence of numbers (or letters) – like dir1, dir2, dir3, and so on – with the following syntax.</p>
<pre><code class="lang-bash">mkdir dir{1..5}
</code></pre>
<p>Now this will create dir1 up to dir5. We can also replace numbers with letters.</p>
<p>Creating nested directories:</p>
<pre><code class="lang-bash">mkdir -p parent/child/grandchild
</code></pre>
<p>The <code>-p</code> option creates nested directories. In this example, it creates a directory structure: parent → child → grandchild.</p>
<h3 id="heading-pwd"><code>pwd</code></h3>
<p>The pwd command stands for "print working directory." It displays the current directory path where you're located within the file system.</p>
<h5 id="heading-example-1">Example:</h5>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
</code></pre>
<h3 id="heading-cd"><code>cd</code></h3>
<p>The cd command is used to change the current working directory. cd stands for <code>Change Directory</code>.</p>
<h5 id="heading-syntax-7">Syntax:</h5>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> [DIRECTORY_PATH]
</code></pre>
<h5 id="heading-examples-8">Examples:</h5>
<p>Changing to a specific directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> /path/to/directory
</code></pre>
<p>This command changes the current directory to given path – for example, /path/to/directory.</p>
<p>Moving to a parent directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ..
</code></pre>
<p><code>..</code> refers to the parent directory, so this command moves one level up from the current directory.</p>
<p>Returning to the home directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span>
</code></pre>
<p>Typing <code>cd</code> without any arguments takes you to your home directory.</p>
<p>Switch to the previous directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> -
</code></pre>
<p>This will take you to the previous directory that you were working on.</p>
<h3 id="heading-cp"><code>cp</code></h3>
<p>The <code>cp</code> command is used to copy files and directories from one location to another.</p>
<h5 id="heading-syntax-8">Syntax:</h5>
<pre><code class="lang-bash">cp [OPTIONS] SOURCE DESTINATION
</code></pre>
<h5 id="heading-examples-9">Examples:</h5>
<p>Copying a file to another location:</p>
<pre><code class="lang-bash">cp file.txt /path/to/destination/
</code></pre>
<p>This command copies file.txt to the specified destination directory (/path/to/destination/).</p>
<p>Copying multiple files to a directory:</p>
<pre><code class="lang-bash">cp file1.txt file2.txt file3.txt /path/to/destination/
</code></pre>
<p>This command copies multiple files (file1.txt, file2.txt, file3.txt) to the specified destination directory.</p>
<p>Copying a directory and its contents:</p>
<pre><code class="lang-bash">cp -r directory1 /path/to/destination/
</code></pre>
<p>The <code>-r</code> (or <code>-R</code>) option is used to copy directories recursively. This command copies directory1 and its contents to the specified destination.</p>
<h3 id="heading-mv"><code>mv</code></h3>
<p>The <code>mv</code> command is used to move or rename files and directories from one location to another.</p>
<h5 id="heading-syntax-9">Syntax:</h5>
<pre><code class="lang-bash">mv [OPTIONS] SOURCE DESTINATION
</code></pre>
<h5 id="heading-examples-10">Examples:</h5>
<p>Moving a file to another location:</p>
<pre><code class="lang-bash">mv file.txt /path/to/destination/
</code></pre>
<p>This command moves file.txt to the specified destination directory (/path/to/destination/). If the destination is a file name, it renames file.txt to that name.</p>
<p>Renaming a file:</p>
<pre><code class="lang-bash">mv old_name.txt new_name.txt
</code></pre>
<p>This command renames old_name.txt to new_name.txt.</p>
<p>Options:</p>
<ul>
<li><p><code>-i</code>: Prompts before overwriting existing files.</p>
</li>
<li><p><code>-u</code>: Moves only when the source is newer than the destination file or when the destination file is missing.</p>
</li>
</ul>
<h3 id="heading-nl"><code>nl</code></h3>
<p>The <code>nl</code> command is used to add line numbers to files or text that's provided as input. It reads text from a file or standard input and by default numbers all the lines in the output, making it easier to reference and work with specific lines within the content.</p>
<h5 id="heading-syntax-10">Syntax:</h5>
<pre><code class="lang-bash">nl [OPTIONS] [FILE]
</code></pre>
<h5 id="heading-examples-11">Examples:</h5>
<p>Numbering lines in a file:</p>
<pre><code class="lang-bash">nl filename
</code></pre>
<p>This command numbers all the lines in the specified file (<code>filename</code>) and outputs the result.</p>
<p>Numbering non-empty lines only:</p>
<pre><code class="lang-bash">nl -ba filename
</code></pre>
<p>This command numbers only non-empty lines (the <code>-b</code> option specifies the numbering style, where <code>a</code> denotes non-empty lines).</p>
<h3 id="heading-head"><code>head</code></h3>
<p>The <code>head</code> command outputs the beginning section of files or input streams.</p>
<h5 id="heading-syntax-11">Syntax:</h5>
<pre><code class="lang-bash">head [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-example-2">Example:</h5>
<p>Displaying the first n lines of a file:</p>
<pre><code class="lang-bash">head -n 10 filename
</code></pre>
<p>This command displays the first 10 lines of the specified file.</p>
<h3 id="heading-tail"><code>tail</code></h3>
<p>The <code>tail</code> command displays the end section of files or input streams.</p>
<h5 id="heading-syntax-12">Syntax:</h5>
<pre><code class="lang-bash">tail [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-example-3">Example:</h5>
<p>Displaying the last n lines of a file:</p>
<pre><code class="lang-bash">tail -n 10 filename
</code></pre>
<p>This command displays the last 10 lines of the specified file.</p>
<h3 id="heading-grep"><code>grep</code></h3>
<p>The <code>grep</code> command in Linux is a powerful utility used for searching text patterns within files or input streams. Its primary function is to scan a specified file or standard input line by line and print lines that match a specified pattern.</p>
<h5 id="heading-syntax-13">Syntax:</h5>
<pre><code class="lang-bash">grep [OPTIONS] PATTERN [FILE(s)]
</code></pre>
<h5 id="heading-examples-12">Examples:</h5>
<p>Searching for a specific pattern in a file:</p>
<pre><code class="lang-bash">grep <span class="hljs-string">"pattern"</span> filename
</code></pre>
<p>This command searches for the word "pattern" in the specified file (<code>filename</code>) and displays the lines containing that pattern.</p>
<p>Case-insensitive search in a file:</p>
<pre><code class="lang-bash">grep -i <span class="hljs-string">"pattern"</span> filename
</code></pre>
<p>This command searches for "pattern" in the specified file (<code>filename</code>) regardless of whether it's in uppercase or lowercase.</p>
<p>Searching for multiple patterns in a file:</p>
<pre><code class="lang-bash">grep -e <span class="hljs-string">"pattern1"</span> -e <span class="hljs-string">"pattern2"</span> filename
</code></pre>
<p>This command searches for both "pattern1" and "pattern2" in the specified file (<code>filename</code>) and displays lines containing either of these patterns. You can also use different files for different pattern matching.</p>
<h3 id="heading-wc"><code>wc</code></h3>
<p>The <code>wc</code> command stands for "word count," but its functionality extends beyond counting words. It's a versatile command-line utility used to count the number of lines, words, and characters in files or standard input streams.</p>
<h5 id="heading-syntax-14">Syntax:</h5>
<pre><code class="lang-bash">wc [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-examples-13">Examples:</h5>
<p>Counting lines in a file:</p>
<pre><code class="lang-bash">wc -l filename
</code></pre>
<p>This command displays the number of lines in the specified file (<code>filename</code>).</p>
<p>Counting words in a file:</p>
<pre><code class="lang-bash">wc -w filename
</code></pre>
<p>This shows the count of words in the specified file.</p>
<p>Counting lines, words, and characters simultaneously:</p>
<pre><code class="lang-bash">wc filename
</code></pre>
<p>By default, this command displays the count of lines, words, and characters in the specified file.</p>
<h5 id="heading-options-and-flags-for-wc">Options and flags for <code>wc</code>:</h5>
<ul>
<li><p><code>-l</code>: Displays the number of lines.</p>
</li>
<li><p><code>-w</code>: Shows the count of words.</p>
</li>
<li><p><code>-m</code>: Outputs the count of characters.</p>
</li>
<li><p><code>-c</code>: Provides byte counts (equivalent to <code>-m</code> in most cases).</p>
</li>
<li><p><code>-L</code>: Displays the length of the longest line.</p>
</li>
<li><p><code>-h</code>: Provides human-readable output (e.g., <code>1.2K</code> for 1200).</p>
</li>
</ul>
<h3 id="heading-cut"><code>cut</code></h3>
<p>The <code>cut</code> command in Linux is used to extract specific sections (columns or portions) of text from files or input streams based on delimiters like characters or fields.</p>
<h5 id="heading-syntax-15">Syntax:</h5>
<pre><code class="lang-bash">cut [OPTIONS] [FILE(s)]
</code></pre>
<h5 id="heading-examples-14">Examples:</h5>
<p>Extracting specific columns from a file:</p>
<pre><code class="lang-bash">cut -d<span class="hljs-string">','</span> -f 1,3 filename.txt
</code></pre>
<p>This command extracts the first and third columns from a CSV file (<code>filename.txt</code>) where columns are delimited by a comma (<code>-d','</code> specifies the delimiter).</p>
<p>Selecting a range of characters from a file:</p>
<pre><code class="lang-bash">cut -c 1-5 filename.txt
</code></pre>
<p>This command extracts characters 1 to 5 from each line of the specified file (<code>filename.txt</code>).</p>
<p>You can always find more options for any command using <code>man you_command</code>. This give give proper documentation for that specified command. <code>man stands for manual.</code></p>
<p>Now that you've learned some commonly used RHEL commands, make sure to practice using them. You can start by working through the below exercise.</p>
<h2 id="heading-how-the-linux-file-system-works">How the Linux File System Works</h2>
<p>In Linux, the root directory <code>/</code> acts as the top level directory in the system hierarchy. It contains various subdirectories, each serving a specific function and storing the necessary system files.</p>
<p>Here is an overview of the primary directories in RHEL and their functions within the root directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Frame-1000004540.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Linux File System</em></p>
<p>Let's go over the function and purpose of each of these directories.</p>
<h3 id="heading-bin-binary"><code>/bin</code> (Binary)</h3>
<ul>
<li><p>Function: contains essential executable binaries (commands) accessible to all users.</p>
</li>
<li><p>Purpose: contains fundamental system commands like <code>ls</code>, <code>cp</code>, <code>mv</code>, <code>rm</code>, and so on.</p>
</li>
</ul>
<h3 id="heading-boot"><code>/boot</code></h3>
<ul>
<li><p>Function: holds files necessary for booting the operating system.</p>
</li>
<li><p>Purpose: contains boot loader files, kernel images, and configuration files required during system boot-up.</p>
</li>
</ul>
<h3 id="heading-dev-device"><code>/dev</code> (Device)</h3>
<ul>
<li><p>Function: represents device files.</p>
</li>
<li><p>Purpose: provides access to physical and virtual devices such as hard drives, USB devices, terminals, and more.</p>
</li>
</ul>
<h3 id="heading-etc-etcetera"><code>/etc</code> (Etcetera)</h3>
<ul>
<li><p>Function: stores system-wide configuration files.</p>
</li>
<li><p>Purpose: contains configuration files for various applications, services, and system settings.</p>
</li>
</ul>
<h3 id="heading-home"><code>/home</code></h3>
<ul>
<li><p>Function: houses user home directories.</p>
</li>
<li><p>Purpose: each user typically has a subdirectory within <code>/home</code> that contains their personal files, settings, and data.</p>
</li>
</ul>
<h3 id="heading-lib-and-lib64"><code>/lib</code> and <code>/lib64</code></h3>
<ul>
<li><p>Function: contains libraries required by programs at runtime.</p>
</li>
<li><p>Purpose: stores shared library files used by system binaries and applications.</p>
</li>
</ul>
<h3 id="heading-mnt-mount"><code>/mnt</code> (Mount)</h3>
<ul>
<li><p>Function: provides a mount point for temporarily mounting external devices.</p>
</li>
<li><p>Purpose: used for mounting external storage devices such as USB drives, network shares, or additional file systems.</p>
</li>
</ul>
<h3 id="heading-opt-optional"><code>/opt</code> (Optional)</h3>
<ul>
<li><p>Function: reserved for optional or third-party software.</p>
</li>
<li><p>Purpose: often used to install large, self-contained software packages that don’t conform to the standard Linux file system hierarchy.</p>
</li>
</ul>
<h3 id="heading-proc-process"><code>/proc</code> (Process)</h3>
<ul>
<li><p>Function: virtual file system providing information about system processes.</p>
</li>
<li><p>Purpose: offers a way to interactively examine and manipulate the system's internal state.</p>
</li>
</ul>
<h3 id="heading-root"><code>/root</code></h3>
<ul>
<li><p>Function: home directory for the superuser (root).</p>
</li>
<li><p>Purpose: contains the root user's files, settings, and configuration files.</p>
</li>
</ul>
<h3 id="heading-sbin-system-binary"><code>/sbin</code> (System Binary)</h3>
<ul>
<li><p>Function: stores essential system administration binaries.</p>
</li>
<li><p>Purpose: contains commands crucial for system administration, often requiring administrative privileges.</p>
</li>
</ul>
<h3 id="heading-srv-service"><code>/srv</code> (Service)</h3>
<ul>
<li><p>Function: intended for data related to services provided by the system.</p>
</li>
<li><p>Purpose: used for storing data and files used by various services running on the system.</p>
</li>
</ul>
<h3 id="heading-tmp-temporary"><code>/tmp</code> (Temporary)</h3>
<ul>
<li><p>Function: directory for temporary files.</p>
</li>
<li><p>Purpose: contains temporary files created by various system processes and users. Files here are typically deleted on system reboot.</p>
</li>
</ul>
<h3 id="heading-usr-unix-system-resources"><code>/usr</code> (Unix System Resources)</h3>
<ul>
<li><p>Function: holds user-related programs, libraries, and documentation.</p>
</li>
<li><p>Purpose: contains a vast majority of user-accessible applications, system utilities, libraries, and documentation.</p>
</li>
</ul>
<h3 id="heading-var-variable"><code>/var</code> (Variable)</h3>
<ul>
<li><p>Function: stores variable data such as logs, spool files, and temporary files.</p>
</li>
<li><p>Purpose: contains data that varies frequently, including system logs, mail, print queues, and more.</p>
</li>
</ul>
<h2 id="heading-text-editors">Text Editors</h2>
<p>There are various terminal-based text editors, each with its own strengths and functionalities. But Vim stands out among these editors due to its unparalleled versatility and robust feature set.</p>
<p>Vim's strength lies in its powerful modal editing, offering distinct modes for navigation, insertion, and executing commands, enabling swift and efficient text manipulation.</p>
<p>Additionally, Vim's syntax highlighting, support for multiple programming languages, and powerful search and replace capabilities make it a preferred choice for programmers and system administrators alike.</p>
<h3 id="heading-vim">vim</h3>
<p>Vim is a popular text editor among Linux users especially within the command line interface. Vim stands for "Vi IMproved" and is an enhanced version of the classic <code>vi</code> editor. It offers extensive features for editing, viewing, and manipulating text or code files.</p>
<p>In this section, we will delve into the world of Vim and how to use it in Linux. My goal is to acquaint you with some practical commands and features within Vim to help you easily manipulate text.</p>
<p>Here's how to open Vim in Linux:</p>
<pre><code class="lang-bash">vim [OPTIONS] [FILE(s)]
</code></pre>
<h3 id="heading-modes-in-vim">Modes in Vim:</h3>
<p>In Vim, modes act as different operational states that dictate how you can engage with the editor. The key modes – Normal, Insert, and Visual – play a significant role in your editing process.</p>
<p>You'll start in Normal mode when you open Vim. From there, you can easily navigate, move the cursor, and execute commands. Switching to Insert mode give you a direct means of inputting and altering text. And Visual mode lets you select and manipulate text blocks.</p>
<p>These modes are critical in streamlining various editing tasks, and can help you become more efficient and accurate. Learning how to use and transition between these modes give you versatile control over text editing and makes you much more productive within the Vim environment.</p>
<ul>
<li><p><strong>Normal Mode:</strong> Default mode for navigation and executing commands.</p>
</li>
<li><p><strong>Insert Mode:</strong> For typing and editing text.</p>
</li>
<li><p><strong>Visual Mode:</strong> For selecting and manipulating blocks of text.</p>
</li>
</ul>
<h3 id="heading-editing-in-insert-mode">Editing in Insert Mode:</h3>
<p>Picture yourself opening a document in Vim, eager to insert new information. Simply hit the <code>i</code> key, and Vim will know you're ready to type at the current cursor position.</p>
<p>A notification at the bottom will alert you with -- INSERT -- signifying that you are officially in insert mode. Now you can input your desired additions. When you're done, hit the 'Esc' key to return to the default mode where you can then navigate and execute commands.</p>
<ul>
<li><p>Press <code>i</code> to enter insert mode and start typing.</p>
</li>
<li><p>Press <code>Esc</code> to exit insert mode and return to command mode.</p>
</li>
</ul>
<h3 id="heading-saving-and-exiting-vim">Saving and Exiting Vim:</h3>
<p>Imagine that you've made some alterations to your document and now you're ready to save them before exiting Vim. Simply type <code>:wq</code> (which represents "write and quit") and hit 'Enter' to securely save your changes and leave Vim.</p>
<p>But what if you've made changes that you don't want to keep? In this situation, enter <code>:q!</code> and press 'Enter' to instruct Vim to quit without saving any modifications made since your last save.</p>
<p>By typing <code>:wq</code> and <code>:q!</code>, depending on your needs, you can confidently add content to your document and ensure that your work is either securely saved or discarded. These actions, paired with your ability to navigate Vim's different modes, make for a seamless and efficient editing experience.</p>
<ul>
<li><p>To save changes and exit, type <code>:wq</code> (write and quit) and press Enter.</p>
</li>
<li><p>To exit without saving changes, type <code>:q!</code> and press Enter.</p>
</li>
</ul>
<h3 id="heading-how-to-edit-commands">How to Edit Commands</h3>
<p>Before you enter any command, press <code>esc</code> so that you are out of any mode that you were in.</p>
<p>In the editor, commands preceded by a colon (for example, <code>:w</code>) are utilized to carry out various actions, such as saving files. To save any modifications you've made, simply type <code>:w</code> and hit the 'Enter' key.</p>
<p>Similarly, commands like <code>dd</code> are designed for tasks such as erasing a line. To delete a line, make sure you are in the appropriate mode (Normal mode), then type <code>dd</code> by pressing the 'd' key twice in rapid succession. If you happen to find yourself in a different mode, simply press the 'esc' key to return to Normal mode.</p>
<h4 id="heading-insert-mode-example">Insert mode example:</h4>
<ul>
<li><code>i</code>: Enter insert mode before the cursor.</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li><p>Use the arrow keys or 'h', 'j', 'k', 'l' to navigate to the end of the first line.</p>
</li>
<li><p>Press 'i' to enter insert mode.</p>
</li>
<li><p>Type your new sentence.</p>
</li>
<li><p>Press 'Esc' to exit insert mode.</p>
</li>
</ul>
<h4 id="heading-deleting-and-changing-text">Deleting and changing text:</h4>
<ul>
<li><p><code>dw</code>: Delete from the cursor to the end of the word.</p>
</li>
<li><p><code>dd</code>: Delete entire line.</p>
</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li><p>Move the cursor to the line you want to delete.</p>
</li>
<li><p>Press <code>dd</code>.</p>
</li>
</ul>
<h4 id="heading-copy-cut-and-paste">Copy, cut, and paste:</h4>
<ul>
<li><p><code>yy</code>: Copy (yank) current line.</p>
</li>
<li><p><code>yw</code>: Copy from the cursor to the end of the word.</p>
</li>
<li><p><code>p</code>: Paste after the cursor.</p>
</li>
<li><p><code>P</code>: Paste before the cursor.</p>
</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li><p>To copy a line: Move the cursor to the line you want to copy and press <code>yy</code>.</p>
</li>
<li><p>To cut (delete) a line: Move the cursor to the line you want to cut and press <code>dd</code>.</p>
</li>
<li><p>To paste the copied or cut line: Move the cursor to the desired location and press <code>p</code> to paste after the cursor or <code>P</code> to paste before the cursor.</p>
</li>
</ul>
<h4 id="heading-searching">Searching:</h4>
<ul>
<li><p><code>/pattern</code>: Search forward for "pattern".</p>
</li>
<li><p><code>?pattern</code>: Search backward for "pattern".</p>
</li>
<li><p><code>n</code>: Move to the next search result.</p>
</li>
<li><p><code>N</code>: Move to the previous search result.</p>
</li>
</ul>
<pre><code class="lang-c">vim example.txt
</code></pre>
<ul>
<li><p>To search for a word like "example": Press <code>/</code> and then type <code>example</code> followed by <code>Enter</code>.</p>
</li>
<li><p>To move to the next occurrence: Press <code>n</code>.</p>
</li>
<li><p>To move to the previous occurrence: Press <code>N</code>.</p>
</li>
</ul>
<h4 id="heading-replace">Replace:</h4>
<ul>
<li><p><code>:%s/old/new/g</code>: Replace "old" with "new" globally in the entire file.</p>
</li>
<li><p><code>:s/old/new/g</code>: Replace "old" with "new" on the current line.</p>
</li>
<li><p><code>:s/old/new/gc</code>: Replace "old" with "new" with confirmation.</p>
</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li>To replace all occurrences of "oldword" with "newword": Type <code>:%s/oldword/newword/g</code> and press <code>Enter</code>.</li>
</ul>
<h4 id="heading-saving">Saving:</h4>
<ul>
<li><p><code>:w</code>: Save changes.</p>
</li>
<li><p><code>:wq</code> or <code>ZZ</code>: Save changes and quit.</p>
</li>
<li><p><code>:x</code>: Save changes and quit (same as <code>:wq</code>).</p>
</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li>To save changes made to the file: Type <code>:w</code> and press <code>Enter</code>.</li>
</ul>
<h4 id="heading-quitting">Quitting:</h4>
<ul>
<li><p><code>:q</code>: Quit (only if there are no unsaved changes).</p>
</li>
<li><p><code>:q!</code>: Quit without saving changes.</p>
</li>
</ul>
<pre><code class="lang-bash">vim example.txt
</code></pre>
<ul>
<li><p>To exit without saving changes: Type <code>:q!</code> and press <code>Enter</code>.</p>
</li>
<li><p>To save changes and quit: Type <code>:wq</code> or <code>ZZ</code> and press <code>Enter</code>.</p>
</li>
</ul>
<h3 id="heading-practical-exercises">Practical Exercises</h3>
<p>Now, to help you practice what you've learned, here are some exercises for you.</p>
<p>Let's say that you've been tasked with organizing and manipulating files and directories on a newly provisioned Red Hat Enterprise Linux system. Use the terminal to complete the following tasks:</p>
<h4 id="heading-essential-command-line-tools-amp-functions">Essential Command Line Tools &amp; Functions:</h4>
<ul>
<li><p>Use <code>echo</code> to display your name and a greeting message using variables and escape sequences.</p>
</li>
<li><p>Use <code>whoami</code> to print the current user's name.</p>
</li>
<li><p>Create a file named <code>example.txt</code> and display its contents using <code>cat</code>.</p>
</li>
<li><p>Use <code>touch</code> to create three files: <code>file1.txt</code>, <code>file2.txt</code>, and <code>file3.txt</code>.</p>
</li>
<li><p>Experiment with <code>ls</code> command variations: <code>-a</code>, <code>-l</code>, <code>-h</code>, <code>-t</code>, and combinations.</p>
</li>
<li><p>Use <code>date</code> to display the current date and then customize the output to a specific format.</p>
</li>
</ul>
<h4 id="heading-linux-file-system-exploration">Linux File System Exploration:</h4>
<ul>
<li><p>Use <code>mkdir</code> to create directories: <code>/bin</code>, <code>/boot</code>, <code>/home</code>, <code>/etc</code>, etc., and explain their functionalities in a document.</p>
</li>
<li><p>Navigate to <code>/var</code> and list its contents.</p>
</li>
<li><p>Use <code>pwd</code> to print the current directory path.</p>
</li>
</ul>
<h4 id="heading-text-editing-with-vim">Text Editing with Vim:</h4>
<ul>
<li><p>Create a file <code>sample.txt</code>.</p>
</li>
<li><p>Open <code>sample.txt</code> using <code>vim</code>.</p>
</li>
<li><p>Practice inserting text, deleting lines, copying and pasting, and saving changes.</p>
</li>
</ul>
<h4 id="heading-file-operations">File Operations:</h4>
<ul>
<li><p>Copy <code>sample.txt</code> to a newly created directory <code>/tmp</code> using <code>cp</code>.</p>
</li>
<li><p>Move <code>sample.txt</code> to the <code>/var</code> directory using <code>mv</code>.</p>
</li>
<li><p>Remove <code>sample.txt</code> from the current directory using <code>rm</code>.</p>
</li>
</ul>
<h4 id="heading-inspecting-file-system-information">Inspecting File System Information:</h4>
<ul>
<li><p>Use <code>ls -l</code> to view detailed information of a file in <code>/usr/bin</code>.</p>
</li>
<li><p>Explain the output and file permissions in a document.</p>
</li>
</ul>
<h4 id="heading-basic-searches-and-text-manipulation">Basic Searches and Text Manipulation:</h4>
<ul>
<li><p>Use <code>grep</code> to search for a specific word in a file.</p>
</li>
<li><p>Perform a search-and-replace operation in <code>example.txt</code> using <code>sed</code>.</p>
</li>
</ul>
<h4 id="heading-advanced-file-management">Advanced File Management:</h4>
<ul>
<li><p>Create nested directories <code>/opt/program/scripts</code> using <code>mkdir -p</code>.</p>
</li>
<li><p>Move <code>file1.txt</code> and <code>file2.txt</code> into <code>/opt/program</code> directory.</p>
</li>
</ul>
<h4 id="heading-reflection-and-documentation">Reflection and Documentation:</h4>
<ul>
<li><p>Reflect on your experience with each command in a document, explaining its usage and outcomes.</p>
</li>
<li><p>Document any challenges faced and their solutions.</p>
</li>
<li><p>Summarize the importance of each concept and command learned.</p>
</li>
</ul>
<p>Remember, while performing these exercises, ensure you're in the correct directory and double-check commands involving file deletion or modification to prevent unintended actions.</p>
<h4 id="heading-review-questions">Review Questions:</h4>
<ol>
<li><p>What command creates a new directory? Execute it.</p>
</li>
<li><p>How do you create multiple files at once? Demonstrate this.</p>
</li>
<li><p>What command moves files from one location to another? Move <code>file1.txt</code> and <code>file3.txt</code> to <code>folderA</code>.</p>
</li>
<li><p>How can you display the current date and time? Show the output.</p>
</li>
<li><p>Which command lists the contents of a directory in detail? Use it for the <code>RHCSA_Practice</code> directory.</p>
</li>
<li><p>Explain the purpose of creating nested directories.</p>
</li>
<li><p>What command renames a file? Rename <code>file2.txt</code> to <code>important_file.txt</code>.</p>
</li>
<li><p>How can you display only the hidden files in a directory? Show the hidden files in your current directory.</p>
</li>
</ol>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thank you for exploring the world of Red Hat Enterprise Linux (RHEL) administration with me today. You can dive deeper into the realm of Linux expertise and stay tuned for more insightful content in my future tutorials.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Styled Components in Your React Apps ]]>
                </title>
                <description>
                    <![CDATA[ Styled-components is a library that allows you to write CSS in JS while building custom components in Reactjs. There are multiple options you can go with to style a React application. But the CSS in JS technique is good approach, where you write the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/styled-components-in-react/</link>
                <guid isPermaLink="false">66d45f74ffe6b1f641b5fa0f</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Thu, 04 May 2023 14:19:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/Frame-390.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Styled-components is a library that allows you to write <code>CSS in JS</code> while building custom components in <code>Reactjs</code>.</p>
<p>There are multiple options you can go with to style a React application. But the <code>CSS in JS</code> technique is good approach, where you write the <code>CSS</code> code right in the <code>JavaScript file</code>. Styled-components takes this approach.</p>
<p>In this article, you will learn how to write CSS in JS.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we go ahead with styled components, you should be familiar with <code>React</code> and <code>CSS</code>.</p>
<h2 id="heading-how-to-create-a-basic-react-app">How to Create a Basic React App</h2>
<p>Before getting started with styled components, let's start by creating a React app using <code>create-react-app</code> .</p>
<pre><code class="lang-javascript">npx create-react-app APP_NAME
</code></pre>
<p>If you are not familiar with create-react-app, you can <a target="_blank" href="https://reactjs.org/docs/create-a-new-react-app.html">check here</a> for more information.</p>
<p>Once you React boiler plate is set, remove all files from <code>src</code> folder except <code>index.js</code> and <code>app.js</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss1-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is how your files should look like when you are done with the above steps. Now it's time to clean up <code>app.js</code> and <code>index.js</code>. Now index.js and app.js will have some default boiler code. We need to remove unnecessary stuff from these files. After removing unnecessary stuff you app.js and index.js should look like code below in respective files.</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            App
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>

<span class="hljs-keyword">const</span> root = ReactDom.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>))
root.render(
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
)
</code></pre>
<p>Now open the command line or press ctrl + <code>(backtick) to open it and type</code>npm start` to start your React app.</p>
<p>Once your app is running successfully, stop your server using ctrl + c and install styled-components. The command to install styled-components is below:</p>
<pre><code class="lang-javascript">npm install styled-components
</code></pre>
<h2 id="heading-lets-style-our-first-component">Let's Style Our First Component</h2>
<p>We will create a basic setup to help you learn styled components. In app.js, create a heading using an</p>
<h1 id="heading-tag-a-paragraph-using-a-tag-and-a-button-using-the-tagappjs-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appbefore-we-style-our-component-we-need-to-import-styled-components-into-our-appjs-fileimport-styled-from-styled-components-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appnow-we-will-create-our-custom-component-called-h1-and-use-it-instead-of-the-tag-with-custom-styling-const-h1-styledh1-color-red-font-size-4rem-first-we-need-give-a-custom-name-of-our-choice-then-well-start-with-styled-and-wrap-the-style-in-backticks-now-when-we-use-this-custom-component-it-will-have-the-property-with-stylingimport-styled-from-styled-components-const-h1-styledh1-color-red-font-size-4rem-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appvoila-here-we-have-our-first-custom-styled-componentnote-always-use-uppercase-letters-to-start-your-custom-component-name-in-react-as-it-is-react-conventionnow-if-you-inspect-the-page-you-will-see-some-gibberish-class-name-styled-components-does-this-to-avoid-naming-conflictsnow-lets-style-our-button-component-const-defaultbutton-styledbutton-background-color-645cfc-border-none-padding-10px-color-white-defaultbutton-is-our-custom-component-name-after-we-style-it-we-can-give-it-any-html-tag-we-desire-so-that-this-custom-component-will-have-that-tagnow-we-will-use-defaultbutton-that-we-created-above-as-our-custom-component-in-reactjs-but-behind-the-scenes-it-will-be-the-button-tag-from-html-as-we-mentioned-in-styling-using-styled-componentsimport-styled-from-styled-components-const-h1-styledh1-color-red-const-defaultbutton-styledbutton-background-color-645cfc-border-none-padding-10px-color-white-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appwe-can-also-keep-our-files-clean-by-making-a-different-file-for-each-different-component-in-styled-components-yes-we-can-do-that-in-herewe-will-make-new-folder-called-components-in-src-and-create-the-files-titlejs-and-buttonsjs-to-separate-the-styling-for-title-and-buttonswe-will-copy-the-h1-style-and-paste-it-into-titlejs-and-copy-defaultbutton-style-and-paste-it-in-buttonsjsin-titlejs-we-will-export-it-as-default-but-in-buttonsjs-we-will-name-the-export-because-we-will-create-multiple-button-styles-in-herewhen-we-are-exporting-a-component-as-default-then-its-import-is-a-regular-import-as-shown-belowimport-h1-from-componentstitlebut-when-the-export-is-a-named-export-you-can-see-the-named-export-in-buttonjs-in-the-above-image-then-while-importing-that-component-we-have-to-wrap-the-component-name-in-curly-braces-as-shown-belowimport-defaultbutton-from-componentsbuttonsnow-our-appjs-looks-like-thisimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appprops-in-styled-componentsnow-for-those-of-you-who-know-props-from-react-youre-in-luck-pops-in-styled-components-work-similarly-if-you-dont-know-what-props-are-dont-worry-ill-introduce-them-herenow-we-learned-to-create-custom-components-in-styled-components-those-custom-components-can-have-attributes-which-we-can-access-in-components-it-might-be-a-bit-confusing-to-beginners-but-lets-see-it-in-codeimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-appin-the-above-code-i-created-one-more-default-button-but-can-you-see-difference-between-those-2-buttons-yes-we-have-something-written-after-defaultbutton-which-is-red-its-called-an-attributenow-by-accessing-the-attribute-in-defaultbutton-we-can-change-the-styling-based-on-these-attributes-lets-do-it-import-styled-from-styled-components-export-const-defaultbutton-styledbutton-background-color-props-gt-propsred-ampamp-red-645cfc-border-none-padding-10px-color-white-we-are-already-in-a-template-literal-backtickshttpsdevelopermozillaorgen-usdocswebjavascriptreferencetemplateliterals-so-we-can-write-javascript-inside-it-we-used-the-dollar-sign-and-curly-braces-to-write-the-javascript-in-those-curly-braces-we-declared-an-arrow-functionhttpsdevelopermozillaorgen-usdocswebjavascriptreferencefunctionsarrowfunctions-which-has-a-props-parameter-which-can-access-attributes-of-custom-componentsso-the-arrow-function-says-that-if-the-red-attribute-is-given-then-the-background-color-should-be-red-or-else-it-should-be-a-blueberry-colorappjsimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-appwe-can-also-destructure-props-by-attribute-name-above-we-gave-defaultbutton-an-attribute-of-red-and-we-accessed-it-with-propsredinstead-of-accessing-it-with-propsred-we-could-destructure-the-prop-with-and-the-attribute-name-refer-to-the-below-code-to-get-a-good-understanding-import-styled-from-styled-components-export-const-defaultbutton-styledbutton-background-color-red-gt-red-ampamp-red-645cfc-border-none-padding-10px-color-white-now-we-can-access-props-directly-as-red-rather-that-propsredhow-to-extend-styles-in-styled-componentswe-know-how-to-write-custom-styled-components-but-what-if-we-want-to-use-the-defaultbuttons-style-that-instead-has-100-width-of-the-button-we-can-do-that-using-extended-styles-in-styled-componentsits-simple-we-just-have-to-create-a-new-component-in-buttonsjs-and-well-use-styled-instead-of-styleddefaultbutton-now-our-new-component-will-have-added-the-styles-of-defaultbutton-and-some-of-new-styles-of-its-ownexport-const-extendedbutton-styleddefaultbutton-display-block-width-100vw-appjsimport-h1-from-componentstitle-import-defaultbutton-extendedbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-apphow-to-nest-styles-in-styled-componentswe-can-write-more-complex-styles-in-react-using-one-custom-component-this-will-help-you-even-more-and-make-styling-simple-refer-to-the-following-codeimport-styled-from-styled-components-function-app-return-another-heading-another-para-another-button-const-wrapper-styleddiv-h1-text-align-center-color-violet-p-font-size-40px-button-background-color-pink-padding-4px-8px-border-none-export-default-appwhen-we-implement-the-wrapper-component-all-paragraph-tags-inside-the-wrapper-will-have-a-font-size-of-40px-and-the-button-will-have-background-color-of-pink-padding-as-mentioned-and-no-border-this-will-help-you-tremendously-when-writing-your-codehow-to-extend-react-componentswe-can-also-extend-react-components-using-styled-components-it-is-pretty-similar-to-nesting-styles-heres-an-exampleimport-react-from-react-import-styled-from-styled-components-const-newcom-gt-return-heading-2-click-me-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-violet-border-none-export-default-wrapperwhen-we-write-styles-using-styled-components-we-have-to-just-extend-react-components-like-extending-styles-when-were-extending-styles-we-write-the-name-of-the-extended-style-here-we-will-write-the-name-of-the-component-to-extend-as-shown-in-the-above-codebut-still-its-not-working-if-we-inspect-we-will-see-our-html-but-with-no-class-in-react-components-there-is-no-class-so-you-need-to-add-props-to-the-react-component-and-consolelog-those-propsyou-will-see-our-gibberish-class-name-with-the-keyvalue-pair-like-classname-gibberish-classname-so-now-using-that-we-will-destructure-the-props-and-give-a-classname-to-the-div-of-that-component-of-classname-refer-to-the-below-exampleimport-react-from-react-import-styled-from-styled-components-const-newcom-classname-gt-return-heading-2-click-me-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-violet-border-none-export-default-wrappereven-after-using-styled-components-for-styling-you-can-use-global-stylingjust-remember-that-if-your-global-styling-and-styled-component-styling-are-the-same-react-will-pick-the-styled-component-stylingcss-variablesrepeating-the-same-color-is-annoying-what-if-i-have-red-in-many-places-and-now-i-want-all-that-red-changed-to-blue-it-is-a-time-consuming-task-to-do-manually-one-by-oneluckily-css-variables-come-to-our-rescue-now-create-an-indexcss-file-in-the-src-folder-import-it-in-indexjsimport-indexcssnow-we-will-write-some-css-variable-in-indexcss-which-are-global-styles-accessible-from-everywhere-the-most-interesting-thing-is-that-we-can-have-access-to-css-variables-in-styled-component-as-wellindexcssroot-primary-color-8f00ff-now-root-is-just-like-selecting-html-in-css-but-root-has-more-specificity-than-html-we-can-now-use-this-variable-in-our-styled-component-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-var-primary-color-border-none-how-to-add-a-themenowadays-light-themes-and-dark-themes-are-pretty-popular-we-can-do-this-easily-in-styles-componentsfirst-we-need-to-import-themeprovider-from-styled-components-then-we-will-wrap-the-whole-app-in-themeprovider-with-the-theme-attribute-in-which-we-will-provide-our-theme-then-we-can-toggled-it-with-reactimport-styled-themeprovider-from-styled-components-import-sample-from-componentssample-const-basetheme-background-fff-color-222-const-darktheme-background-222-color-fff-function-app-return-this-is-sample-paragraph-still-we-dont-get-our-dark-theme-for-that-we-need-to-add-a-new-custom-styled-component-you-can-name-it-anything-you-want-but-im-gonna-name-it-containerin-the-container-we-can-access-the-theme-and-its-properties-and-help-the-user-change-the-background-color-and-color-of-text-these-are-the-only-major-things-to-switch-in-between-dark-and-light-modeimport-styled-themeprovider-from-styled-components-import-sample-from-componentssample-const-basetheme-background-fff-color-222-const-darktheme-background-222-color-fff-const-container-styleddiv-color-props-gt-propsthemecolor-background-color-props-gt-propsthemebackground-function-app-return-this-is-sample-paragraph-take-a-look-at-our-container-we-are-accessing-the-theme-and-changing-the-color-and-background-color-when-the-theme-changes-and-here-you-go-a-simple-way-to-have-themes-on-your-next-projectanimation-in-styled-componentsanimation-is-important-in-frontend-development-we-will-learn-to-implement-animation-in-styled-components-with-an-examplefirst-we-have-to-import-keyframes-from-styled-components-once-thats-done-we-will-use-it-to-create-animationsimport-styled-keyframes-from-styled-components-const-spinner-keyframes-to-transform-rotate360deg-const-loading-styleddiv-width-6rem-height-6rem-border-5px-solid-ccc-border-radius-50-border-top-color-black-animation-spinner-06s-linear-infinite-export-default-loadingin-the-above-code-we-have-spinner-in-which-we-declared-the-animation-and-spinner-is-the-animation-name-in-loading-we-are-using-that-spinner-animation-name-so-that-loading-will-use-that-animation-in-loading-i-have-use-a-shorthand-property-to-declare-the-animationhow-to-use-as-in-styled-componentsif-i-have-a-button-and-i-give-it-an-href-attribute-which-we-use-to-link-to-another-website-it-will-not-work-this-is-because-the-href-attribute-belongs-to-the-anchor-tagimport-react-from-react-import-defaultbutton-from-componentsbuttons-const-app-gt-return-click-export-default-appbut-in-styles-component-using-as-we-can-make-the-given-component-act-like-an-html-tag-provided-as-a-value-to-as-lets-see-it-in-actionimport-react-from-react-import-defaultbutton-from-componentsbuttons-const-app-gt-return-click-export-default-appnow-defaultbutton-is-an-anchor-tag-it-will-have-text-decoration-because-in-the-default-anchor-tag-it-has-text-decoration-but-i-am-sure-now-you-can-work-that-out-when-we-click-on-our-defaultbutton-it-will-open-googlecss-and-styled-componentsnow-we-can-directly-give-styles-to-components-using-css-as-an-object-of-the-component-called-css-props-import-react-from-react-import-styled-from-styled-components-const-app-gt-return-hello-world-export-default-appbut-the-above-code-wont-work-because-we-need-to-import-styled-componentsmacro-to-activate-the-styling-method-which-uses-babel-check-out-the-complete-code-belowimport-react-from-react-import-styled-from-styled-componentsmacro-const-app-gt-return-hello-world-export-default-appcss-helper-functions-in-styled-componentswe-have-learned-a-lot-about-styled-components-but-there-are-more-efficient-ways-to-tackle-some-problems-and-one-of-them-is-using-a-css-helper-functionsuppose-you-want-a-defaultbutton-and-a-large-defaultbutton-based-on-what-weve-learned-up-until-now-we-would-say-we-should-give-large-as-a-prop-and-change-the-styling-based-on-that-propbut-think-about-it-we-need-to-make-changes-to-multiple-properties-so-a-css-helper-function-comes-to-our-rescue-appjsimport-react-from-react-import-styled-from-styled-componentsmacro-import-defaultbutton-from-componentsbuttons-const-app-gt-return-hello-hello-export-default-appbuttonsjsimport-styled-css-from-styled-componentsmacro-export-const-defaultbutton-styledbutton-background-color-red-gt-red-ampamp-red-645cfc-border-none-color-white-display-block-margin-10px-large-gt-large-css-padding-15px-font-weight-800-css-padding-10px-font-weight-400-take-a-look-at-the-above-code-first-we-passed-a-prop-as-large-from-appjs-in-defaultbutton-component-then-using-the-ternary-operator-in-buttonjs-we-styled-the-component-it-says-that-if-large-is-given-a-prop-implement-the-first-styling-or-else-implement-the-second-styling-this-follows-the-dry-dont-repeat-yourself-principledefault-attributes-attrs-in-styled-componentswe-have-attributes-on-some-elements-in-html-for-example-on-button-we-have-typesubmit-or-typebutton-but-every-time-we-have-to-set-them-manuallyimport-react-from-react-import-styled-from-styled-components-const-button-styledbutton-border-none-padding-5px-10px-background-color-87cd11-margin-10px-const-app-gt-return-click-submit-export-default-apphere-default-attributes-come-in-handy-we-can-pass-an-object-or-function-to-them-but-if-we-pass-objects-to-attributes-then-they-will-be-static-to-have-dynamic-control-we-will-pass-a-function-to-the-attributeimport-react-from-react-import-styled-from-styled-components-const-button-styledbuttonattrsprops-gt-return-type-propstype-button-border-none-padding-5px-10px-background-color-87cd11-margin-10px-const-app-gt-return-click-submit-export-default-appin-the-above-code-we-set-attributes-to-button-this-says-that-if-the-type-is-given-then-it-will-set-that-type-to-the-given-props-or-if-no-props-are-given-it-will-set-it-to-button-by-defaultas-a-challenge-you-can-go-ahead-and-use-a-css-helper-function-to-set-a-different-style-based-on-the-type-of-buttonwrapping-upi-hope-you-now-understand-how-to-use-styled-components-in-your-projects-do-let-me-know-what-you-think-thank-you-for-readingyou-can-follow-me-ontwitterhttpstwittercomkedar98linkedinhttpswwwlinkedincominkedar-makode-9833321aboriginalsubdomainininstagramhttpswwwinstagramcomkedar98">tag, a paragraph using a tag and a button using the tag.<code>App.js function App() { return ( &lt;div&gt; &lt;h1&gt;Styled Components&lt;/h1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Before we style our component, we need to import styled-components into our <code>app.js</code> file:<code>import styled from 'styled-components' function App() { return ( &lt;div&gt; &lt;h1&gt;Styled Components&lt;/h1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Now we will create our <strong>custom component</strong> called H1 and use it instead of the tag with custom styling.<code>const H1 = styled.h1` color: red; font-size: 4rem; ` </code>First we need give a custom name of our choice. Then we'll start with <code>styled.&lt;HTML Tag Name&gt;</code> and wrap the style in backticks. Now when we use this custom component it will have the <code>&lt;HTML Tag Name&gt;</code> property with styling.<code>import styled from 'styled-components' const H1 = styled.h1` color: red; font-size: 4rem; ` function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Voilà! Here we have our first custom styled component.<strong>NOTE</strong>: Always use uppercase letters to start your custom component name in React as it is React convention.Now if you inspect the page, you will see some gibberish class name. Styled components does this to avoid naming conflicts.Now let's style our button component:<code>const DefaultButton = styled.button` background-color: #645cfc; border: none; padding: 10px; color: white; ` </code>DefaultButton is our custom component name. After we style it, we can give it any HTML tag we desire so that this custom component will have that tag.Now we will use DefaultButton that we created above as our custom component in React.js – but behind the scenes it will be the button tag from HTML as we mentioned in styling using styled components.<code>import styled from 'styled-components' const H1 = styled.h1` color: red; ` const DefaultButton = styled.button` background-color: #645cfc; border: none; padding: 10px; color: white; ` function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>We can also keep our files clean by making a different file for each different component in styled components. Yes! We can do that in here.We will make new folder called <code>components</code> in <code>src</code> and create the files <code>Title.js</code> and <code>Buttons.js</code> to separate the styling for title and buttons.We will copy the H1 style and paste it into <code>Title.js</code> and copy DefaultButton style and paste it in <code>Buttons.js</code>.In <code>Title.js</code> we will export it as default. But in <code>Buttons.js</code> we will name the export because we will create multiple button styles in here.When we are exporting a component as default, then its import is a regular import as shown below:<code>import H1 from './components/Title'</code>But when the export is a named export (you can see the named export in Button.js in the above image), then while importing that component we have to wrap the component name in curly braces ({}) as shown below:<code>import {DefaultButton} from './components/Buttons'</code>Now our <code>App.js</code> looks like this:<code>import H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>Props in Styled ComponentsNow for those of you who know props from React, you're in luck – pops in styled components work similarly. If you don't know what props are, don't worry – I'll introduce them here.Now, we learned to create custom components in styled components. Those custom components can have attributes which we can access in components. It might be a bit confusing to beginners but let's see it in code:<code>import H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;DefaultButton red&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>In the above code, I created one more Default button. But can you see difference between those 2 buttons. Yes! We have something written after DefaultButton, which is <code>red</code>. It's called an attribute.Now by accessing the attribute in DefaultButton we can change the styling based on these attributes. Let's do it!<code>import styled from 'styled-components' export const DefaultButton = styled.button` background-color: ${(props) =&gt; (props.red &amp;&amp; 'red') || '#645cfc'}; border: none; padding: 10px; color: white; ` </code>We are already in a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literal (backticks)</a>. So we can write JavaScript inside it. We used the dollar ($) sign and curly braces to write the JavaScript. In those curly braces we declared an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a> which has a props parameter which can access attributes of custom components.So the arrow function says that if the <strong>red</strong> attribute is given, then the background-color should be red or else it should be a blueberry color.<code>App.jsimport H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;DefaultButton red&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>We can also destructure props by attribute name. Above, we gave DefaultButton an attribute of red and we accessed it with <code>props.red</code>.Instead of accessing it with <code>props.red</code> we could destructure the prop with {} and the attribute name. Refer to the below code to get a good understanding.<code>import styled from 'styled-components' export const DefaultButton = styled.button` background-color: ${({red}) =&gt; (red &amp;&amp; 'red') || '#645cfc'}; border: none; padding: 10px; color: white; ` </code>Now we can access props directly as <code>red</code> rather that <code>props.red</code>.How to Extend Styles in Styled ComponentsWe know how to write custom styled components. But what if we want to use the DefaultButtons style that instead has 100% width of the button? We can do that using extended styles in styled components.It's simple: we just have to create a new component in <code>Buttons.js</code> . And we'll use <code>styled.&lt;html Tag&gt;</code>, instead of <code>styled(DefaultButton)</code>. Now our new component will have added the styles of DefaultButton and some of new styles of its own.<code>export const ExtendedButton = styled(DefaultButton)` display: block; width: 100vw; `App.jsimport H1 from './components/Title' import {DefaultButton, ExtendedButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;ExtendedButton red&gt;Click ME!&lt;/ExtendedButton&gt; &lt;/div&gt; ); } export default App;</code>How to Nest Styles in Styled ComponentsWe can write more complex styles in React using one custom component. This will help you even more and make styling simple. Refer to the following code:<code>import styled from 'styled-components' function App() { return ( &lt;div&gt; &lt;Wrapper&gt; &lt;h1&gt;Another heading&lt;/h1&gt; &lt;p&gt;Another para&lt;/p&gt; &lt;button&gt;Another button&lt;/button&gt; &lt;/Wrapper&gt; &lt;/div&gt; ); } const Wrapper = styled.div` h1{ text-align: center; color: violet; } p{ font-size: 40px; } button{ background-color: pink; padding: 4px 8px; border: none; } ` export default App;</code>When we implement the wrapper component, all paragraph tags inside the wrapper will have a font-size of 40px and the button will have background color of pink, padding as mentioned, and no border. This will help you tremendously when writing your code.How to Extend React ComponentsWe can also extend React components using styled components. It is pretty similar to nesting styles. Here's an example:<code>import React from 'react' import styled from 'styled-components' const Newcom = () =&gt; { return ( &lt;div&gt; &lt;h2&gt;Heading 2&lt;/h2&gt; &lt;button&gt;Click Me!&lt;/button&gt; &lt;/div&gt; ) } const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: violet; border: none; } ` export default Wrapper</code>When we write styles using styled components, we have to just extend React components like extending styles. When we're extending styles, we write the name of the extended style. Here we will write the name of the component to extend as shown in the above code.But still it's not working. If we inspect we will see our HTML but with no class. In React components there is no class. So you need to add props to the React component and console.log() those props.You will see our gibberish class name with the key:value pair, like className : gibberish-classname. So now using that we will destructure the props and give a className to the div of that component of className. Refer to the below example:<code>import React from 'react' import styled from 'styled-components' const Newcom = ({className}) =&gt; { return ( &lt;div className={className}&gt; &lt;h2&gt;Heading 2&lt;/h2&gt; &lt;button&gt;Click Me!&lt;/button&gt; &lt;/div&gt; ) } const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: violet; border: none; } ` export default Wrapper</code>Even after using styled components for styling you can use global styling.Just remember that if your global styling and styled component styling are the same, React will pick the styled component styling.CSS VariablesRepeating the same color is annoying. What if I have red in many places and now I want all that red changed to blue? It is a time consuming task to do manually, one by one.Luckily, CSS variables come to our rescue. Now create an <code>index.css</code> file in the <code>src</code> folder. Import it in <code>index.js</code>.<code>import './index.css';</code>Now we will write some CSS variable in index.css which are global styles accessible from everywhere. The most interesting thing is that we can have access to CSS variables in styled component as well.<code>index.css:root{ --primary-color: #8F00FF }</code>Now <code>:root{}</code> is just like selecting <code>html{}</code> in CSS. But <code>:root{}</code> has more specificity than <code>html{}</code>. We can now use this variable in our styled component:<code>const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: var(--primary-color); border: none; } ` </code>How to Add a ThemeNowadays, light themes and dark themes are pretty popular. We can do this easily in styles components.First we need to import ThemeProvider from styled components. Then we will wrap the whole app in ThemeProvider with the theme attribute in which we will provide our theme. Then we can toggled it with React.<code>import styled, {ThemeProvider} from 'styled-components' import Sample from "./components/Sample"; const baseTheme = { background: '#fff', color: '#222', } const darkTheme = { background: '#222', color: '#fff', } function App() { return ( &lt;ThemeProvider theme={darkTheme}&gt; &lt;p&gt;This is sample paragraph&lt;/p&gt; &lt;/ThemeProvider&gt; ); }</code>Still, we don't get our dark theme. For that we need to add a new custom styled component. You can name it anything you want but, I'm gonna name it <code>Container</code>.In the container, we can access the theme and its properties and help the user change the background color and color of text. These are the only major things to switch in between dark and light mode.<code>import styled, {ThemeProvider} from 'styled-components' import Sample from "./components/Sample"; const baseTheme = { background: '#fff', color: '#222', } const darkTheme = { background: '#222', color: '#fff', } const Container = styled.div` color: ${(props) =&gt; props.theme.color}; background-color: ${(props) =&gt; props.theme.background}; ` function App() { return ( &lt;ThemeProvider theme={darkTheme}&gt; &lt;Container&gt; &lt;p&gt;This is sample paragraph&lt;/p&gt; &lt;/Container&gt; &lt;/ThemeProvider&gt; ); }</code>Take a look at our <code>Container</code>. We are accessing the theme and changing the color and background-color when the theme changes. And here you go, a simple way to have themes on your next project.Animation in Styled ComponentsAnimation is important in frontend development. We will learn to implement animation in styled components with an example.First we have to import keyframes from styled-components. Once that's done we will use it to create animations.<code>import styled, {keyframes} from 'styled-components' const spinner = keyframes` to{ transform: rotate(360deg); } ` const Loading = styled.div` width: 6rem; height: 6rem; border: 5px solid #ccc; border-radius: 50%; border-top-color: black; animation: ${spinner} 0.6s linear infinite; ` export default Loading</code>In the above code, we have spinner in which we declared the animation and spinner is the animation name. In loading, we are using that spinner animation name so that Loading will use that animation. In loading I have use a shorthand property to declare the animation.How to Use <code>as</code> in Styled ComponentsIf I have a button and I give it an <code>href</code> attribute which we use to link to another website, it will not work. This is because the <code>href</code> attribute belongs to the anchor tag.<code>import React from 'react' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton href="https://www.google.com"&gt;Click&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default App</code>But in styles component using <code>as</code> we can make the given component act like an HTML tag provided as a value to <code>as</code>. Let's see it in action.<code>import React from 'react' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton as='a' href="https://www.google.com"&gt;Click&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default App</code>Now DefaultButton is an anchor () tag. It will have text-decoration because in the default anchor tag it has text-decoration. But I am sure now you can work that out. When we click on our DefaultButton it will open Google.CSS and styled-componentsNow we can directly give styles to components using CSS as an object of the component called <code>css props</code> .<code>import React from 'react' import styled from 'styled-components' const App = () =&gt; { return ( &lt;div&gt; &lt;h2 css={`color: green`}&gt;Hello World!!!&lt;/h2&gt; &lt;/div&gt; ) } export default App</code>But the above code won't work. Because we need to import styled-components/macro to activate the styling method which uses Babel. Check out the complete code below:<code>import React from 'react' import styled from 'styled-components/macro' const App = () =&gt; { return ( &lt;div&gt; &lt;h2 css={`color: green`}&gt;Hello World!!!&lt;/h2&gt; &lt;/div&gt; ) } export default App</code>CSS Helper Functions in Styled ComponentsWe have learned a lot about styled components. But there are more efficient ways to tackle some problems – and one of them is using a CSS helper function.Suppose you want a DefaultButton and a large DefaultButton. Based on what we've learned up until now, we would say we should give large as a prop and change the styling based on that prop.But think about it – we need to make changes to multiple properties. So a CSS helper function comes to our rescue.<code>App.jsimport React from 'react' import styled from 'styled-components/macro' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton&gt;Hello&lt;/DefaultButton&gt; &lt;DefaultButton large&gt;Hello&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default AppButtons.jsimport styled, {css} from 'styled-components/macro' export const DefaultButton = styled.button` background-color: ${({red}) =&gt; (red &amp;&amp; 'red') || '#645cfc'}; border: none; color: white; display: block; margin: 10px; ${({large}) =&gt; large? css` padding: 15px; font-weight: 800; ` : css` padding: 10px; font-weight: 400; `} ` </code>Take a look at the above code. First we passed a prop as large from app.js in DefaultButton component. Then using the ternary operator in Button.js we styled the component. It says that if <code>large</code> is given a prop, implement the first styling or else implement the second styling. This follows the DRY (Don't Repeat Yourself) principle.Default Attributes (attrs) in Styled ComponentsWe have attributes on some elements in HTML. For example on button, we have type="submit" or type="button". But every time we have to set them manually.<code>import React from 'react' import styled from 'styled-components' const Button = styled.button` border: none; padding: 5px 10px; background-color: #87CD11; margin: 10px; ` const App = () =&gt; { return ( &lt;div&gt; &lt;Button type="button"&gt;Click!&lt;/Button&gt; &lt;Button type="submit"&gt;Submit&lt;/Button&gt; &lt;/div&gt; ) } export default App</code>Here, default attributes come in handy. We can pass an object or function to them. But if we pass objects to attributes, then they will be static. To have dynamic control, we will pass a function to the attribute.<code>import React from 'react' import styled from 'styled-components' const Button = styled.button.attrs((props) =&gt; { return {type: props.type || "button"} })` border: none; padding: 5px 10px; background-color: #87CD11; margin: 10px; ` const App = () =&gt; { return ( &lt;div&gt; &lt;Button&gt;Click!&lt;/Button&gt; &lt;Button type="submit"&gt;Submit&lt;/Button&gt; &lt;/div&gt; ) } export default App</code>In the above code, we set attributes to <code>button</code>. This says that if the type is given then it will set that type to the given props – or if no props are given it will set it to button by default.As a challenge, you can go ahead and use a CSS helper function to set a different style based on the type of button.<strong>Wrapping Up</strong>I hope you now understand how to use Styled Components in your projects. Do let me know what you think. Thank you for reading!You can follow me on:<a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></h1>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous JavaScript Works ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn all about Asynchronous JavaScript. But before we dive into that, we need to make sure you understand what Synchronous code is and how it works. What is Synchronous Code? When we write a program in JavaScript, it execute... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript/</link>
                <guid isPermaLink="false">66d45f6347a8245f78752a74</guid>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 17 Feb 2023 18:37:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-zhang-kaiyv-1168940.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn all about Asynchronous JavaScript.</p>
<p>But before we dive into that, we need to make sure you understand what Synchronous code is and how it works.</p>
<h2 id="heading-what-is-synchronous-code">What is Synchronous Code?</h2>
<p>When we write a program in JavaScript, it executes line by line. When a line is completely executed, then and then only does the code move forward to execute the next line.</p>
<p>Let's look at an example of this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">1000000000</span>;i++){
}
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>Now if you run the above example on your machine you will notice that <code>greet_one</code> logs first. Then the program waits for a couple of seconds and then logs <code>greet_two</code>. This is because the code executes line by line. This is called synchronous code.</p>
<p>This creates lot of problems. For example, if a certain piece of code takes 10 seconds to execute, the code after it won't be able to execute until it's finished, causing delays.</p>
<h2 id="heading-what-is-asynchronous-code">What is Asynchronous Code?</h2>
<p>With asynchronous code, multiple tasks can execute at the same time while tasks in the background finish. This is what we call non-blocking code. The execution of other code won't stop while an asynchronous task finishes its work.</p>
<p>Let's see an example of asynchronous code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greet_one = <span class="hljs-string">"Hello"</span>
<span class="hljs-keyword">let</span> greet_two = <span class="hljs-string">"World!!!"</span>
<span class="hljs-built_in">console</span>.log(greet_one)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Asynchronous"</span>);
}, <span class="hljs-number">10000</span>)
<span class="hljs-built_in">console</span>.log(greet_two);
</code></pre>
<p>In the above example, if you run the code on your machine you will see <code>greet_one</code> and <code>greet_two</code> logged even there is code in between those 2 logs.</p>
<p>Now, setTimeout is asynchronous so it runs in background, allowing code after it to execute while it runs. After 10 seconds, <code>Asynchronous</code> will print because we set a time of 10 seconds in setTimeout to execute it after 10 seconds.</p>
<p>In this tutorial, we will study asynchronous JavaScript in detail so you can learn how to write your own asynchronous code. I just wanted to give you a taste of async JavaScript using in-built functions to whet your appetite.</p>
<h1 id="heading-how-callbacks-work-in-javascript">How Callbacks Work in JavaScript</h1>
<blockquote>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."</a> (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">MDN</a>)</p>
</blockquote>
<p>Let's look at a code example to see why using callbacks instead would be helpful:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">compute</span>(<span class="hljs-params">action, x, y</span>)</span>{
    <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"add"</span>){
        <span class="hljs-keyword">return</span> x+y
    }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(action === <span class="hljs-string">"divide"</span>){
        <span class="hljs-keyword">return</span> x/y
    }
}

<span class="hljs-built_in">console</span>.log(compute(<span class="hljs-string">"add"</span>,<span class="hljs-number">10</span>,<span class="hljs-number">5</span>))   
<span class="hljs-built_in">console</span>.log(compute(<span class="hljs-string">"divide"</span>,<span class="hljs-number">10</span>,<span class="hljs-number">5</span>))
</code></pre>
<p>In the above example, we have two operations. But what if we want to add more operations? Then the number of if/else statements would increase. This code would be lengthy, so we use callbacks instead:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">x,y</span>)</span>{
    <span class="hljs-keyword">return</span> x+y
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divide</span>(<span class="hljs-params">x,y</span>)</span>{
    <span class="hljs-keyword">return</span> x/y
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">compute</span>(<span class="hljs-params">callBack, x, y</span>)</span>{
    <span class="hljs-keyword">return</span> callBack(x,y)
}

<span class="hljs-built_in">console</span>.log(compute(add, <span class="hljs-number">10</span>, <span class="hljs-number">5</span>))    <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(compute(divide, <span class="hljs-number">10</span>, <span class="hljs-number">5</span>))
</code></pre>
<p>Now when we call <code>compute</code> with three arguments, one of them is an operation. When we enter in the compute function, the function returns a function with a given action name. It, in response, calls that function and returns the result.</p>
<h2 id="heading-welcome-to-callback-hell">Welcome to Callback Hell</h2>
<p>Callbacks are great, but you don't want to use them excessively. If you do, you'll get something called "callback hell". This happens when you nest callbacks within callbacks many levels deep.</p>
<p>The shape of callback hell is like a pyramid and is also called the “pyramid of doom”. It makes the code very difficult to maintain and understand. Here's an example of callback hell:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"One Second"</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Two Seconds"</span>);
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Three Seconds"</span>);
            <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Four Seconds"</span>);
                <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
                    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Five Seconds"</span>);
                }, <span class="hljs-number">1000</span>)
            }, <span class="hljs-number">1000</span>)
        }, <span class="hljs-number">1000</span>)
    }, <span class="hljs-number">1000</span>)
}, <span class="hljs-number">1000</span>)
</code></pre>
<p>When one second has passed, the code logs "one seconds". Then there's another call which runs after one more second and logs "two seconds" and it goes on and on.</p>
<p>We can escape this callback hell using something call <code>Promises</code> in asynchronous JavaScript.</p>
<h1 id="heading-how-promises-work-in-javascript">How Promises Work in JavaScript</h1>
<p>A promise is placeholder for the future result of an asynchronous operation. In simple words, we can say it is a container for a future value.</p>
<p>When using promises, we don't need to relay on callbacks which helps us avoid callback hell.</p>
<p>Before showing you how promises work through code, I'll explain promises using the analogy of a lottery ticket.</p>
<p>Promises are like lottery ticket. When we buy a lottery ticket, it says we will get money if our outcome is right. This is like a promise. The lottery draw happens asynchronously, and if the numbers match, we receive the money which was promised.</p>
<p>Now let's look at a code example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>)
<span class="hljs-built_in">console</span>.log(request);
</code></pre>
<p>The above code is using fetch for a request from an API. It returns a promise which will get a response from the server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/1212.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is how a promise looks. It has a particular promise state and result. When a promise is created it runs asynchronously. When the given task is completed, then we say the promise is settled. After the promise is settled, we can have either a fulfilled or rejected promise state based on the outcome of the promise. We can handle these different states in different ways in our code.</p>
<h3 id="heading-how-to-consume-promises">How to Consume Promises</h3>
<p>We can consume a promise using the then() method on the promise. Producing code is code that can take some time to complete. Consuming code is code that must wait for the result.</p>
<p>So if we consume a promise, this means that when we make a request, we wait for the result. Then after result arrives, we perform some operation on those results.</p>
<p>Let's continue using the above example to understand how we can consume a promise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(response);
    <span class="hljs-keyword">return</span> response.json()
}).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(data);
})
</code></pre>
<p>We make a request to the country API. Then, after the fetch request, we use the <code>then()</code> method to consume the promise. After that, we return a bunch of information like header, status, and so on (you can see it in the below output image).</p>
<p>So we specifically need data which we need to convert to JSON which returns a promise. The data which is returned when we make a API request gets returned in the form of a promise.</p>
<p>To handle that promise, we again use the then() method to log data from the response. Using multiple <code>then()</code> methods on a single request is called <strong>chaining promises.</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/121212.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-handle-rejected-promises">How to Handle Rejected Promises</h2>
<p>Consuming promises is good and all, but it's also very important to learn how to handle rejected promises. In real world situations, there could be times when our app crashes due to not handling rejected promises properly.</p>
<p>So let's take an example: we will put our promises in a function called <code>call()</code>. In HTML, we will create a button and add an event listener to it. When we click on the button it will call the <code>call()</code> function.</p>
<p>Here's what that looks like:</p>
<p><code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Promises<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Request<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><code>script.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>Why are we doing this? We are setting the promise up to get rejected. Once we run this code, go to inspect and select the network tab. Set No throttling to offline and click on the button to send the request. You will get a rejected promise.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/1111.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once we click on the button, we will get error which is caused by no internet connection.</p>
<p>This situation can happen in the real world if a user's internet connection is slow. We are making an API request for which we need internet with decent speed. Sometimes the client might have an issue with their internet. This can lead to rejected promises which will throw an error which we haven't seen how to handle yet.</p>
<p>Now we will learn to handle this error. We used then() to consume our promises. Similar to that, we will chain the <code>catch()</code> method to that promise. Take a look at the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
        alert(err);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>Now the <code>catch()</code> method will get an error from the rejected promise and will display the message in an alert.</p>
<p>We get the error because we got a rejected promise which indicates that there is some issue. We can do whatever we want in the catch() block when we encounter an error.</p>
<p>Along with the catch() method, there is one more helpful method called <code>finally()</code>. We can chain it to promises which will run no matter whether the promise is accepted or rejected.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">call</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">const</span> request = fetch(<span class="hljs-string">'https://course-api.com/react-store-products'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(response);
        <span class="hljs-keyword">return</span> response.json()
    }).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(data);
    }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(err);
    }).finally(<span class="hljs-function">() =&gt;</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Will always run"</span>);
    })

}

<span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>)
btn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    call();
})
</code></pre>
<p>We can use this <code>finally()</code> method for clearing things after the API call. There are many ways to use the <code>finally()</code> method.</p>
<h2 id="heading-how-to-create-a-promise">How to Create a Promise</h2>
<p>We know how to consume promises, but what about creating your own promises? You can do that using <code>new Promise()</code>.</p>
<p>You might wonder - why do we need our own promises? Firstly, promises are asynchronous in nature. We can create any task to be asynchronous by creating our own promises. Wecan handle them using the <code>then()</code> and <code>catch()</code> methods that we learned in the above section.</p>
<p>Once you know how to create promises, you can make any piece of code asynchronous. Then it will not block code execution if the other code running is taking a long time to complete.</p>
<p>Let's see how this works using an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> lottery = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Lottery is happening"</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">Math</span>.random() &gt;= <span class="hljs-number">0.5</span>){
            resolve(<span class="hljs-string">"You Won!!!"</span>)
        }
        <span class="hljs-keyword">else</span>{
            reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Better luck next time"</span>))
        }
    }, <span class="hljs-number">5000</span>);

})
</code></pre>
<p>First we created a promise using <code>new Promise()</code>. It will have a function with two arguments, <code>resolve</code> and <code>reject</code>.</p>
<p>We will call <code>resolve</code> when our task is successful, and <code>reject</code> when the task is unsuccessful. We will use the lottery terminology that I used to explain the concept of promises in the above section.</p>
<p>Let's say if <code>Math.random()</code> gives a value below or equal to 0.5, we will win the lottery. Otherwise we will lose the lottery. If the condition is not true, the code throws a new error for better understanding of the error in the console. So we can throw our own custom errors to the user for better understanding.</p>
<p>In the example above, if <code>Math.random()</code> is less than 0.5, that means the user lost the lottery. So we throw our custom error <code>Better luck next time</code> so that the user understands that they lost the lottery.</p>
<p>Now we will try to consume the promise that we created.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> lottery = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Lottery is happening"</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {    
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">Math</span>.random() &gt;= <span class="hljs-number">0.5</span>){
            resolve(<span class="hljs-string">"You Won!!!"</span>)
        }
        <span class="hljs-keyword">else</span>{
            reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Better luck next time"</span>))
        }   
    }, <span class="hljs-number">5000</span>);

})

lottery.then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(response);
}).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(err);
})
</code></pre>
<p>We consume the promise using the <code>then()</code> method. It will print the response that we provided in <code>resolve()</code>. If the promise is rejected we will catch the error in the <code>catch()</code> method. The error will come from the <code>reject()</code> argument that we mentioned in our own promise.</p>
<h3 id="heading-how-to-consume-promises-using-asyncawait">How to Consume Promises using Async/await</h3>
<p>Consuming promises using the then() method can become messy sometimes. So we have an alternative method to consume promises called async/await.</p>
<p>Just keep in mind that async/await will be using the <code>then()</code> method behind the scenes to consume promises.</p>
<p>Why use async/await if we have the <code>then()</code> method? We use async/await because it's easy to use. If we start chaining methods to promises using the <code>then()</code> method the chain will be very long and gets complex with the addition of multiple then() methods. So async/await is simpler.</p>
<p>Here's how async/await works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
    <span class="hljs-built_in">console</span>.log(data);
}
fetchAPI()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST"</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/123123.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the above code, we first call the fetchAPI() to see the async behavior of the function. Then it logs "FIRST". So according to asynchronous JavaScript, fetchAPI() should be running in the background and not block the execution of the code. As a result, "FIRST" logs and then the result of fetchAPI is displayed.</p>
<p>Now, if you want to handle asynchronous tasks in your functions, you have to make that function asynchronous using the async keyword before the function. Wherever promises are returned we have to use await before it to consume promises.</p>
<p>Now you might be thinking, how should we handle errors? For that we can use try...catch() to handle errors in async/await.</p>
<h1 id="heading-error-handling-with-trycatch">Error Handling with <code>try...catch()</code></h1>
<p>We can use <code>try...catch()</code> in vanilla JavaScript as well. But it can also help us handle errors in asynchronous JavaScript with async/await.</p>
<p><code>try...catch()</code> is similar to the <code>catch()</code> method in <code>then()</code> using the <code>catch()</code> chaining method. Here we will try the code in the <code>try</code> block. If that runs successfully then there is no problem.</p>
<p>But if the code in the <code>try</code> block has an error, we can catch it in the <code>catch</code> block. We can check for errors in the try block and throw our custom error which will be caught in <code>catch</code> block. Once we catch the error in the <code>catch</code> block we can do whatever we want when we encounter an error.</p>
<p>Let's see how it works with the code example we've been using.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/fact'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
    }
}


fetchAPI()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST"</span>);
</code></pre>
<p>First, we wrap the asynchronous code in a <code>try</code> block. Then in the <code>catch</code> block we log the error. In the try block, if <code>res.ok</code> is false we throw our custom error using <code>throw new Error</code> which <code>catch</code> will get. Then we log it to the console.</p>
<h1 id="heading-how-to-return-values-from-async-functions">How to Return Values from Async Functions</h1>
<p>So far, we've learned about asynchronous code, the <code>then()</code> and <code>catch()</code> methods, and handling asynchronous code with async/await. But what if we want to return a value from an async function using async/await?</p>
<p>When you're working with asynchronous code, it's often necessary to return a value from an <code>async</code> function so that other parts of your program can use the result of the asynchronous operation.</p>
<p>For example, if you're making an HTTP request to fetch data from an API, you'll want to return the response data to the calling function so that it can be processed or displayed to the user.</p>
<p>Well, we can do that. Take a look at the below example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


<span class="hljs-built_in">console</span>.log(fetchAPI())
</code></pre>
<p>If we log the fetchAPI we will get back a promise which is fullfilled. You know very well how to handle these promises. We will be doing it using the <code>then()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://cat-fact.herokuapp.com/facts'</span>)
        <span class="hljs-keyword">if</span>(!res.ok){
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
        }
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json()
        <span class="hljs-built_in">console</span>.log(data);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


fetchAPI().then(<span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(msg);
}).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(err);
})
</code></pre>
<p>Now when we run our program, we will see our returned msg from the <code>try</code> block using async/await logged in the console.</p>
<p>But what if there was an error in async/await? The fetchAPI with the then() method will still log it and it would be undefined.</p>
<p>To avoid this in the catch block again we throw a new error and use the catch() method to catch that error after the then() method.</p>
<p>Try changing the <code>then()</code> and <code>catch()</code> methods with async/await. This would be a good exercise for you to understand what you've learned in this article.</p>
<p>In JavaScript, there are two common ways to work with asynchronous operations: <code>then/catch</code> method chaining and <code>async/await</code>. Both methods can be used to handle promises, which are objects that represent the eventual completion (or failure) of an asynchronous operation.</p>
<p><code>then/catch</code> method chaining is a more traditional way to handle asynchronous operations, while <code>async/await</code> is a newer syntax that provides a more concise and easier-to-read alternative.</p>
<h2 id="heading-how-to-run-promises-in-parallel">How to Run Promises in Parallel</h2>
<p>Let's say we want to make three requests for three different country capitals. We can do three different fetch calls, each of which will wait for the one above to complete.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchAPI = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">country1,country2,country3</span>)</span>{
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">const</span> res1 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country1}</span>`</span>)
        <span class="hljs-keyword">const</span> res2 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country2}</span>`</span>)
        <span class="hljs-keyword">const</span> res3 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://restcountries.com/v3.1/name/<span class="hljs-subst">${country3}</span>`</span>)


        <span class="hljs-keyword">const</span> data1 = <span class="hljs-keyword">await</span> res1.json()
        <span class="hljs-keyword">const</span> data2 = <span class="hljs-keyword">await</span> res2.json()
        <span class="hljs-keyword">const</span> data3 = <span class="hljs-keyword">await</span> res3.json()
        <span class="hljs-built_in">console</span>.log(data1[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-built_in">console</span>.log(data2[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-built_in">console</span>.log(data3[<span class="hljs-number">0</span>].capital[<span class="hljs-number">0</span>]);
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Done with fetchAPI"</span>
    } <span class="hljs-keyword">catch</span>(err){
        <span class="hljs-built_in">console</span>.log(err);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Custom Error"</span>)
    }
}


fetchAPI(<span class="hljs-string">"canada"</span>, <span class="hljs-string">"germany"</span>, <span class="hljs-string">"russia"</span>)
</code></pre>
<p>In the above code, we are making three fetch calls, then converting them to json() and logging their capitals.</p>
<p>But if you hit inspect and see in the network tab, res2 is waiting for res1 to complete and res3 is waiting for res2 to complete.</p>
<p>This can negatively impact our application's performance. Because if a promise is waiting for another promise to complete it can negatively impact the performance of the website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/321.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To overcome this performance issue, we can use something called <code>**Promise.all**</code> . It will call three fetch requests simultaneously, which in return will reduce our fetching time and improve our application's performance.</p>
<h2 id="heading-how-to-use-promiseall">How to Use Promise.all()</h2>
<p>With the help of Promise.all(), we can run multiple promises in parallel which will boost performance. The promise.all() takes an array as an argument which are promises and run them in parallel.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span>{
       resolve(<span class="hljs-string">"First Promise"</span>)
    }, <span class="hljs-number">2000</span>)
})

<span class="hljs-keyword">let</span> promise2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"Second Promise"</span>)

<span class="hljs-keyword">let</span> returnedPromises = <span class="hljs-built_in">Promise</span>.all([promise1,promise2]).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(res);
})
</code></pre>
<p>The result of using promise.all() is that both promises were running in parallel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/2121.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>After reading this tutorial, I hope you have a better understanding of asynchronous JavaScript. Feel free to reach out to me for discussion and suggestions.</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
<li><p><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Object-Oriented Programming in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Object-Oriented Programming is a programming style based on classes and objects. These group data (properties) and methods (actions) inside a box. OOP was developed to make code more flexible and easier to maintain. JavaScript is prototype-based proc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/object-oriented-programming-javascript/</link>
                <guid isPermaLink="false">66d45f70264384a65d5a9564</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Thu, 09 Feb 2023 02:04:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Frame-389.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Object-Oriented Programming is a programming style based on classes and objects. These group data (properties) and methods (actions) inside a box.</p>
<p>OOP was developed to make code more flexible and easier to maintain.</p>
<p>JavaScript is prototype-based procedural language, which means it supports both functional and object-oriented programming.</p>
<h1 id="heading-what-are-classes-and-objects-in-javascript">What are Classes and Objects in JavaScript?</h1>
<h2 id="heading-what-is-a-class">What is a Class?</h2>
<p>You can think of a class like a blueprint of a house. A class is not a real world object but we can create objects from a class. It is like an template for an object.</p>
<p>We can create classes using the <code>class</code> keyword which is reserved keyword in JavaScript. Classes can have their own properties and methods. We will study how to create a class in detail shortly. This is just a high level overview of a class.</p>
<p>Let's take an example. Below is a blueprint for a house (like a class).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/blueprint.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Blueprint of House (Class)</em></p>
<h2 id="heading-what-is-an-object">What is an Object?</h2>
<p>An object is an instance of a class. Now with the help of the house class we can construct a house. We can construct multiple houses with the help of same house class.</p>
<h3 id="heading-example-of-classes-and-objects-in-action">Example of Classes and Objects in Action</h3>
<p>Let's take a simple example to understand how classes and objects work.</p>
<p>The below example has nothing to do with JavaScript syntax. It is just to explain classes and objects. We will study the syntax of OOP in JavaScript in a bit.</p>
<p>Consider a Student class. Student can have properties like name, age, standard, and so on, and functions like study, play, and do home work.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span></span>{
 <span class="hljs-comment">// Data (Properties)</span>
 Name
 Age
 Standard

 <span class="hljs-comment">// Methods (Action)</span>
 study(){
 <span class="hljs-comment">// Study</span>
 }

 Play(){
 <span class="hljs-comment">// Play</span>
 }

 doHomeWork(){
 <span class="hljs-comment">// Do Home Work</span>
 }

}
</code></pre>
<p>With the help of the above class, we can have multiple students or instances.</p>
<p><strong>Here's info for</strong> <code>**Student - 01**</code><strong>:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Student 1</span>
{
Name = <span class="hljs-string">"John"</span>
Age = <span class="hljs-number">15</span>
Standard = <span class="hljs-number">9</span>

study(){
 <span class="hljs-comment">// Study</span>
 }

 Play(){
 <span class="hljs-comment">// Play</span>
 }

 doHomeWork(){
 <span class="hljs-comment">// Do Home Work</span>
 }

}
</code></pre>
<p><strong>Here's info for</strong> <code>**Student - 02**</code><strong>:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Student 2</span>
{
Name = <span class="hljs-string">"Gorge"</span>
Age = <span class="hljs-number">18</span>
Standard = <span class="hljs-number">12</span>

study(){
 <span class="hljs-comment">// Study</span>
 }

 Play(){
 <span class="hljs-comment">// Play</span>
 }

 doHomeWork(){
 <span class="hljs-comment">// Do Home Work</span>
 }

}
</code></pre>
<h1 id="heading-how-do-we-actually-design-a-class">How Do We Actually Design a Class?</h1>
<p>There is no perfect answer to this question. But we can get help from some OOP principles when designing our classes.</p>
<p>There are 4 main principles in OOP, and they are:</p>
<ul>
<li><p>Abstraction</p>
</li>
<li><p>Encapsulation</p>
</li>
<li><p>Inheritance</p>
</li>
<li><p>Polymorphism</p>
</li>
</ul>
<p>We will dive deep into these concepts in JavaScript below. But first, let's get a high level overview of these concepts to understand them better.</p>
<h2 id="heading-what-does-abstraction-mean-in-oop">What Does Abstraction Mean in OOP?</h2>
<p>Abstraction means hiding certain details that don't matter to the user and only showing essential features or functions.</p>
<p>For example, take a cell phone. We don't show details like <code>verifyTemperature()</code>, <code>verifyVolt()</code>, <code>frontCamOn()</code>, <code>frontCamOff()</code> and so on. Instead we provide essential features which matter to user like camera(), volumeBtn(), and others.</p>
<h2 id="heading-what-does-encapsulation-mean-in-oop">What Does Encapsulation Mean in OOP?</h2>
<p>Encapsulation means keeping properties and methods private inside a class, so that they are not accessible from outside that class.</p>
<p>This will keep code that's outside the class from accidentally manipulating internal methods and properties.</p>
<h2 id="heading-what-does-inheritance-mean-in-oop">What Does Inheritance Mean in OOP?</h2>
<p>Inheritance makes all properties and methods available to a child class. This allows us to reuse common logic and to model real-world relationships. We will discuss inheritance in further section of this article with pratical example.</p>
<h2 id="heading-what-does-polymorphism-mean-in-oop">What Does Polymorphism Mean in OOP?</h2>
<p>Polymorphism means having different and many forms. We can overwrite a method inherited from a parent class.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Not actual JavaScript syntax</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
email 
password

login(providedPassword){
    <span class="hljs-comment">// Login User</span>
}

checkMessage(){
<span class="hljs-comment">// Check any new message</span>
}
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Not actual JavaScript syntax</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Admin</span> <span class="hljs-title">inherit</span> <span class="hljs-title">user</span></span>{
email <span class="hljs-comment">// Inherited Property</span>
password <span class="hljs-comment">// Inherited Property</span>
permissions <span class="hljs-comment">// Own Property</span>

<span class="hljs-comment">// Inherited Method</span>
login(providedPassword){
    <span class="hljs-comment">// Different Login User</span>
}

<span class="hljs-comment">// Inherited Method</span>
checkMessage(){
<span class="hljs-comment">// Check any new message</span>
}

<span class="hljs-comment">// Own Method</span>
chechStats(){
<span class="hljs-comment">// Check Stats</span>
}
}
</code></pre>
<p>The Login method in Admin is different from the inherited class <code>user</code>.</p>
<h1 id="heading-object-oriented-programming-in-javascript">Object-Oriented Programming in JavaScript</h1>
<p>We have now discussed the basics of OOP. But OOP in JavaScript is bit different. We have an object linked to a prototype. Prototypes contain all methods and these methods are accessible to all objects linked to this prototype. This is called <strong>Prototypal Inheritance</strong> (or <strong>Prototypal Delegation</strong>).</p>
<h2 id="heading-what-is-prototypal-inheritance-in-javascript">What is Prototypal Inheritance in JavaScript?</h2>
<p>You have likely already used Prototypal Inheritance without knowing it – for example, if you've used methods on arrays like push(), pop(), map() and so on (which are available on all arrays).</p>
<p>If we go to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">official documentation</a> we will see Array.prototype.map() because Array.prototype is a prototype of all array objects that we create in JavaScript. This is an example of prototypal inheritance that we are going to learn to implement.</p>
<p>Just like Array.prototype we will create our own prototypes and this will help you understand JavaScript inside out.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype of an Array</em></p>
<h2 id="heading-how-to-implement-prototypal-inheritance-in-javascript">How to Implement Prototypal Inheritance in JavaScript</h2>
<p>There are three main ways to implement Prototypal Inheritance in JavaScript:</p>
<h3 id="heading-using-constructor-functions">Using Constructor Functions</h3>
<p>We can create objects from a function. With the help of a constructor function, built-in objects like arrays, sets, and others are actually implemented.</p>
<p>In JavaScript, a constructor gets called when an object is created using the <code>new</code> keyword. The purpose of a constructor is to create a new object and set its values for any existing object properties</p>
<h3 id="heading-using-es6-classes">Using ES6 Classes</h3>
<p>Classes are an alternative to the constructor function syntax for implementing prototypal inheritance. We also call classes <code>syntactic sugar</code>.</p>
<p>Behind the scenes, classes work exactly like constructor functions. Prior to ES6, JavaScript had no concepts of classes. To mock a class, you often use the <a target="_blank" href="https://www.javascripttutorial.net/javascript-constructor-prototype/">constructor or prototype pattern</a>.</p>
<h3 id="heading-using-objectcreate">Using Object.create()</h3>
<p>This is the easiest way to link an object to a prototype object. It is a method used to create a new object with the specified prototype object and properties.</p>
<p>The object.create() method returns a new object with the specified prototype object and properties.</p>
<p>Let's look at these in more detail now:</p>
<h2 id="heading-how-to-implement-prototypal-inheritance-with-constructor-functions-in-javascript">How to Implement Prototypal Inheritance with Constructor Functions in JavaScript</h2>
<p>We will use a function to create prototypal inheritance. We will start by implementing a User function expression. Remember to always start the name of a constructor function with capital letter (standard convention).</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name</span>)</span>{
    <span class="hljs-built_in">this</span>.name = name;

    <span class="hljs-comment">// never create function inside constructor function</span>
    <span class="hljs-built_in">this</span>.printName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }

    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}


<span class="hljs-keyword">let</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
</code></pre>
<p><strong>Output</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss2-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype using constructor function</em></p>
<p>We created a constructor function in the above example. But what is the <code>new</code> keyword? With the help of the new keyword we can create an instance of that constructor.</p>
<p>When we create an instance of the constructor object, an empty object is created ({}). This empty object ({}) is then linked to the prototype.</p>
<p>We should never create a function inside of a constructor function. Because every time an instance is created, a new function is created with it which we created inside the constructor function. This will create major issues for performance.</p>
<p>The solution to this problem is prototypes. We can define a function on the prototype of an object directly. So the object created by using that constructor function will have access to that function.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name</span>)</span>{
    <span class="hljs-built_in">this</span>.name = name;

    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}

User.prototype.printName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)
}


<span class="hljs-keyword">let</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss3-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype using constructor function</em></p>
<p>In the above output, you can see the <code>printName()</code> method in the prototype of the User constructor function. This is the preferred way to create a function in a constructor function to optimize performance.</p>
<p>So now all objects created by this constructor function will have access to the printName() function.</p>
<p>We can access these functions with objectName.functionName() like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name</span>)</span>{
    <span class="hljs-built_in">this</span>.name = name;

    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}

User.prototype.printName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)
}


<span class="hljs-keyword">let</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
kedar.printName()
</code></pre>
<p>We can access the prototype of the constructor function with the following syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(User.__proto__)
</code></pre>
<p>The object prototype is the same as the constructor function prototype. Don't believe me? Check this out:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(kedar.__proto__ === User.prototype) 
<span class="hljs-comment">// True</span>

<span class="hljs-built_in">console</span>.log(User.prototype.isPrototypeOf(kedar))
<span class="hljs-comment">// True</span>
</code></pre>
<p>The prototype of User is the prototype used by its object and doesn't belong to User.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(User.prototype.isPrototypeOf(User))
<span class="hljs-comment">// False</span>
</code></pre>
<p>We can also link a variable to prototype:</p>
<pre><code class="lang-javascript">User.prototype.species = <span class="hljs-string">"Homo Sapiens"</span>
</code></pre>
<p>Now this variable belong to prototype and not to object. We can check this by using <code>hasOwnProperty()</code>.</p>
<h3 id="heading-prototypal-inheritance-of-built-in-objects">Prototypal Inheritance of Built-in Objects</h3>
<p>We have many methods available to use on arrays. How does this work?</p>
<p>The answer is prototypal inheritance. When we create a new array, every time it inherits from Array.prototype. That is how we have access to all those different methods.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-built_in">console</span>.log(arr)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss5-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype of an Array</em></p>
<p>We can also attach our own method to Array.prototype so that whenever we create new array we will have access to that method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">5</span>]

<span class="hljs-built_in">Array</span>.prototype.unique = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> [...new <span class="hljs-built_in">Set</span>(<span class="hljs-built_in">this</span>)]
}

<span class="hljs-built_in">console</span>.log(arr.unique());
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss6-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype of an Array with custom unique() method added to prototype.</em></p>
<h2 id="heading-how-to-implement-prototypal-inheritance-with-es6-classes-in-javascript">How to Implement Prototypal Inheritance with ES6 Classes in JavaScript</h2>
<p>We can implement OOP using classes, but behind the scenes it uses prototypal inheritance. This method was introduced to make sense to people coming from other languages like C++ and Java.</p>
<p>We will implement the User classes from the above example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Class Expression</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>= <span class="hljs-class"><span class="hljs-keyword">class</span></span>{

}

<span class="hljs-comment">// Class Declaration</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{

}
</code></pre>
<p>In the above example, we can see that there are 2 ways to implement a class in JavaScript. You can choose either one according to your preference.</p>
<p>Inside the class, the first thing we need to do is add a constructor method. The constructor can also take arguments.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name){
        <span class="hljs-built_in">this</span>.name = name
    }

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss7-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype using ES6 Class</em></p>
<p>Remember that whenever we create an object of a class, a constructor is invoked first. If there is no constructor, the default constructor is invoked which does nothing.</p>
<h3 id="heading-3-things-to-remember-about-classes">3 things to remember about classes</h3>
<ul>
<li><p>Classes are not hoisted (if you don't know what hoisting is, <a target="_blank" href="https://www.freecodecamp.org/news/javascript-execution-context-and-hoisting/">read this guide</a>)</p>
</li>
<li><p>Classes are first-class citizens (If a programming language has the ability to pass a function as an argument – to treat functions as values and to return functions – it is said that the language has first-class functions and those function are called first-class citizens)</p>
</li>
<li><p>Classes are executed in strict mode. (If you don't know what strict mode is, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">read this guide</a>)</p>
</li>
</ul>
<h3 id="heading-what-are-setters-and-getters">What are Setters and Getters?</h3>
<p>These are simple methods of classes which will get and set a value. But from the outside they look like simple methods. Let's take a look at the below example.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name){
        <span class="hljs-built_in">this</span>._name = name
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">getName</span>(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>._name)
    }

    <span class="hljs-keyword">set</span> <span class="hljs-title">setName</span>(<span class="hljs-params">newName</span>){
        <span class="hljs-built_in">this</span>._name = newName
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
kedar.setName = <span class="hljs-string">"John"</span>
kedar.getName
</code></pre>
<p>In above example, you can see the getter <code>getName</code> logs a name. Setters are used to set the value of an existing property. When setting a name using setter, we have to use (_) before the name of the property as a convention.</p>
<h3 id="heading-how-to-use-static-methods">How to Use Static Methods</h3>
<p>Static methods are bound to a class and not to the instances of class or object of the class. We can access static methods through classes only and not through the object of that class.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name){
        <span class="hljs-built_in">this</span>._name = name
    }

    <span class="hljs-keyword">static</span> anonymous(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"anonymous"</span>);
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
kedar.anonymous() <span class="hljs-comment">// error</span>
User.anonymous() <span class="hljs-comment">// "anonymous"</span>
</code></pre>
<p>We can directly create static methods inside classes using the static keyword before the method name. In the above example, notice that we can only call the static method on a class and not on a class object.</p>
<p>There is one more way to implement a static method:</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>{</span>
    constructor(name){
        <span class="hljs-keyword">this</span>._name = name
    }
}

User.anonymous = function(){
    console.<span class="hljs-built_in">log</span>(<span class="hljs-string">"anonymous"</span>);
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>)
kedar.anonymous() <span class="hljs-comment">// error</span>
User.anonymous() <span class="hljs-comment">// "anonymous"</span>
</code></pre>
<h2 id="heading-how-to-implement-prototypal-inheritance-with-objectcreate-in-javascript">How to Implement Prototypal Inheritance with Object.create() in JavaScript</h2>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">The <code>Object.create()</code> static method creates a new object, using an existing object as the prototype of the newly created object.</a></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> User = {
    init(name){
        <span class="hljs-built_in">this</span>.name = name
    },

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-keyword">let</span> kedar = <span class="hljs-built_in">Object</span>.create(User)
kedar.init(<span class="hljs-string">"kedar"</span>)
kedar.printName()
</code></pre>
<p>The newly created object will inherit all the prototype object's properties. You can specify a second parameter to add new properties to the object, that the prototype lacked:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = <span class="hljs-built_in">Object</span>.create(prototype, newProperties)
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> User = {

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-keyword">let</span> properties = {
    <span class="hljs-attr">name</span>: {
        <span class="hljs-attr">value</span>:<span class="hljs-string">"John"</span>
    }

}

<span class="hljs-keyword">let</span> John = <span class="hljs-built_in">Object</span>.create(User,properties)
John.printName()
</code></pre>
<h2 id="heading-how-inheritance-works-in-javascript">How Inheritance Works in JavaScript</h2>
<p>Inheritance enables you to define a class/object that takes all the functionality from a parent class/object and allows you to add more. Using class inheritance, a class/object can inherit all the methods and properties of another class. It is a useful feature that allows code reusability.</p>
<p>Now we will take a look at inheritance in the constructor function, ES6 classes, and Object.create().</p>
<h3 id="heading-constructor-function">Constructor Function</h3>
<p>Let's understand constructor function inheritance by example. If you don't know how inheritance works at a high level, check out the section where we discussed "How Do We Actually Design a Class".</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> User = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, password</span>)</span>{

    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.password = password
}

User.prototype.printName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
}

<span class="hljs-keyword">const</span> Admin = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, password</span>)</span>{
    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.password = password
}

Admin.prototype.Stats = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Stats"</span>);
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> Admin(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">12345</span>)
kedar.Stats()
</code></pre>
<p>In the above code, we have 2 constructor functions, and they have some similarities. Still we wrote it twice which violates the DRY (Don't Repeat Yourself) principle. To avoid repeating the same code, we use inheritance.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> User = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, password</span>)</span>{

    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.password = password
}

User.prototype.printName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
}

<span class="hljs-keyword">const</span> Admin = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, password, course</span>)</span>{
    User.call(<span class="hljs-built_in">this</span>, name, password)
    <span class="hljs-built_in">this</span>.course = course
}

Admin.prototype = <span class="hljs-built_in">Object</span>.create(User.prototype)

Admin.prototype.Stats = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Stats"</span>);
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> Admin(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">12345</span>, <span class="hljs-string">"JavaScript"</span>)
kedar.printName()
</code></pre>
<p>In the above code, first in the Admin (child) function we attached <code>this</code> to the User (parent) and called it with parameters. Once we did that, we were able to access the name and password fields. But we were not able to access the methods of the parent function. Because we need to connect the prototype of User and Admin.</p>
<p>For that, just after the child function, we pointed the Admin prototype to the User prototype which gave us access to the methods of the parent function (User).</p>
<p>Make sure to point the child (Admin) prototype to the parent (User) function immediately after the child (Admin) function. Because it returns an empty object and removes all methods on the child (Admin) function. So always create methods of the child (Admin) function after pointing the child (Admin) prototype to the parent (User) prototype.</p>
<p>Now let's see how our prototype chain looks:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss8-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype Inheritance using constructor function</em></p>
<p>At the bottom there is an Object prototype. After that we can see there is a User prototype and at the top we see an Admin prototype.</p>
<h3 id="heading-es6">ES6</h3>
<p>It is super simple to implement inheritance using ES6 syntax. But remember ES6 uses constructor functions to implement inheritance behind the scenes.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.password  =password
    }

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Admin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password, course){
        <span class="hljs-built_in">super</span>(name, password)
        <span class="hljs-built_in">this</span>.course = course
    }

    Stats(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Stats"</span>);
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> Admin(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>, <span class="hljs-string">"JavaScript"</span>)
kedar.printName()
</code></pre>
<p>So we have 2 classes, User and Admin. When we want to inherit, we simply add <code>extends</code> and the class we want to inherit from in-front of the child class similar to the syntax shown in the above code.</p>
<p>When we are done with that, in the constructor of the child class, we call the <code>super()</code> method to pass an argument to the parent class which is required. That's how we can implement inheritance in JavaScript using ES6 syntax.</p>
<p>We can also <code>override</code> the parent method by implementing a method with the same name in the child class.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.password  =password
    }

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Admin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password, course){
        <span class="hljs-built_in">super</span>(name, password)
        <span class="hljs-built_in">this</span>.course = course
    }

    Stats(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Stats"</span>);
    }

    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Child class "</span> + <span class="hljs-built_in">this</span>.name)
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> Admin(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>, <span class="hljs-string">"JavaScript"</span>)
kedar.printName()
</code></pre>
<h3 id="heading-objectcreate">Object.create()</h3>
<p>Implementing inheritance in Object.create() is simple. Check out the code below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> User = {
    printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    },

    init(name, password){
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.password = password
    }
}

<span class="hljs-keyword">const</span> Admin = <span class="hljs-built_in">Object</span>.create(User)
Admin.init = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name, password, course</span>)</span>{
    User.init.call(<span class="hljs-built_in">this</span>, name, password)
    <span class="hljs-built_in">this</span>.course = course
}

Admin.stats = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Stats"</span>);
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-built_in">Object</span>.create(Admin)
kedar.init(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>)
kedar.printName()
kedar.stats()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss9-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Prototype Inheritnace using Object.create()</em></p>
<p>First, we created a User function. Then we created an Admin pointing to User with the help of <code>Object.create()</code>. With the help of the <code>Admin.init()</code> method we called the <code>init()</code> method of User and passed values to the parent function.</p>
<h2 id="heading-how-encapsulation-works-in-javascript">How Encapsulation Works in JavaScript</h2>
<p>Above, we looked at what encapsulation means at a very high level. Now we will look at an example to explain it more thoroughly.</p>
<p>Encapsulation can be defined as <em>“the packing of data and functions into one component”.</em> This is also known as grouping or bundling, and simply means to bring together data and the methods which operate on data. It can be a function, a class, or an object.</p>
<p>Encapsulation enables “<em>controlling access to that component</em>”. When we have the data and related methods in a single unit, we can control how is it accessed outside the unit. This process is called Encapsulation**.**</p>
<h3 id="heading-protected-properties">Protected properties</h3>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>._name = name
        <span class="hljs-built_in">this</span>._password = password
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>)
<span class="hljs-built_in">console</span>.log(kedar._password);
</code></pre>
<p>A protected member is accessible within the class and any object that inherits from it. A protected value is shared across all layers of the prototype chain.</p>
<p>We used (_) in <code>this._name</code> , which is a protected property. We can still access this property outside of the class. This is just a convention programmers use.</p>
<p>If we know there is (_) in a property name we are not supposed to manipulate that property from outside the class.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>._name = name
        <span class="hljs-built_in">this</span>._password = password
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">getName</span>(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>._name)
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>)
kedar.getName
</code></pre>
<h3 id="heading-private-properties">Private properties</h3>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>.#name = name
        <span class="hljs-built_in">this</span>._password = password
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">getName</span>(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>._name)
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>)
<span class="hljs-built_in">console</span>.log(kedar.#name);
</code></pre>
<p>To implement a truly private property in JavaScript we have to use (#) before the property name or method. These private properties and methods will not be accessible from outside of class which will make them truly private.</p>
<p>This will help restrict accessing properties from outside of the class. If we want to access property from outside we have to make method which will only print properties without giving access to change value of that property.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>{
    #name

    <span class="hljs-keyword">constructor</span>(name, password){
        <span class="hljs-built_in">this</span>.#name = name
        <span class="hljs-built_in">this</span>._password = password
    }

    #printName(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.#name);
    }

    PrintFromPrivateMethod(){
        <span class="hljs-built_in">this</span>.#printName()
    }
}

<span class="hljs-keyword">const</span> kedar = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"kedar"</span>, <span class="hljs-number">123456</span>)
kedar.PrintFromPrivateMethod()
</code></pre>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>I hope you now understand how OOP works in JavaScript. Thank you for reading!</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
<li><p><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
