<?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[ Zaira Hira - 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[ Zaira Hira - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 16 May 2026 10:45:47 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/zaira/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Get Information About Your Linux System Through the Command Line ]]>
                </title>
                <description>
                    <![CDATA[ Whether you’ve just gained access to a new Linux system, ethically hacked into one as part of a security test, or you’re just curious to know more about your current machine, this article will guide you through the process. You’ll learn how you can g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/get-linux-system-info-through-cli/</link>
                <guid isPermaLink="false">68495738cb7b75f7a33a73c4</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cli ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 11 Jun 2025 10:15:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749636399891/4b457f71-2d18-463a-b98a-e19ff5a6b769.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Whether you’ve just gained access to a new Linux system, ethically hacked into one as part of a security test, or you’re just curious to know more about your current machine, this article will guide you through the process.</p>
<p>You’ll learn how you can get information related to your OS (operating system), kernel, CPU, memory, processes, disks, networks, and installed software. You’ll explore the commands and their outputs in detail.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-its-important-to-understand-your-linux-system">Why It's Important to Understand Your Linux System</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-os-amp-kernel-information-in-linux">How to Get Your OS &amp; Kernel Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-cpu-information-in-linux">How to Get Your CPU Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-memory-information-in-linux">How to Get Your Memory Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-disk-amp-filesystem-information-in-linux">How to Get Your Disk &amp; Filesystem Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-hardware-information-in-linux">How to Get Your Hardware Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-network-interfaces-amp-status-information-in-linux">How to Get Your Network Interfaces &amp; Status Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-software-amp-services-information-in-linux">How to Get Your Software &amp; Services Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-logs-amp-dmesg-in-formation-in-linux">How to Get Your Logs &amp; Dmesg In formation in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-your-securityuser-audit-information-in-linux">How to Get Your Security/User Audit Information in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-visually-appealing-commands">Visually Appealing Commands</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-why-its-important-to-understand-your-linux-system">Why It's Important to Understand Your Linux System</h2>
<h3 id="heading-system-administration">System Administration</h3>
<p>System administrators need to have an understanding of the system so they are able to:</p>
<ul>
<li><p>Manage users, groups, and permissions effectively.</p>
</li>
<li><p>Configure services like web servers, databases, and so on.</p>
</li>
<li><p>Automate repetitive tasks with scripts and cron jobs.</p>
</li>
</ul>
<h3 id="heading-troubleshooting">Troubleshooting</h3>
<p>When the system is in a problematic state, a solid understanding of the system specification and configuration helps you to:</p>
<ul>
<li><p>Identify and resolve system errors quickly.</p>
</li>
<li><p>Analyze system logs and monitor performance.</p>
</li>
<li><p>Diagnose network and hardware issues.</p>
</li>
</ul>
<h3 id="heading-security-auditing">Security Auditing</h3>
<p>If you are in a security related role, knowing your system in depth helps you to:</p>
<ul>
<li><p>Monitor logs for unauthorized access.</p>
</li>
<li><p>Configure firewalls and security policies.</p>
</li>
<li><p>Detect and remove malicious processes or software.</p>
</li>
</ul>
<h3 id="heading-performance-optimization">Performance Optimization</h3>
<p>If you know how to gather information related to system resources, you can measure them and create a projection for the future use. You can also:</p>
<ul>
<li><p>Tune system parameters for better efficiency.</p>
</li>
<li><p>Monitor resource usage (CPU, memory, disk, I/O).</p>
</li>
<li><p>Eliminate bottlenecks and optimize workloads.</p>
</li>
</ul>
<h3 id="heading-proactive-maintenance">Proactive Maintenance</h3>
<p>It is a good practice to be able to prevent issues before they occur. Once you know your system well, you can:</p>
<ul>
<li><p>Schedule regular updates and backups.</p>
</li>
<li><p>Ensure system reliability and uptime.</p>
</li>
</ul>
<p>Understanding your Linux system gives you greater control, enhances system stability, and improves your overall effectiveness as a system administrator or power user.</p>
<p>In the next section, we’ll discuss some essential commands for gathering system information.</p>
<h2 id="heading-how-to-get-your-os-amp-kernel-information-in-linux">How to Get Your OS &amp; Kernel Information in Linux</h2>
<h3 id="heading-uname-a-command"><code>uname -a</code> Command</h3>
<p><code>uname -a</code> provides full kernel information:</p>
<pre><code class="lang-bash">uname -a
Linux ip-172-31-90-178 6.8.0-1024-aws <span class="hljs-comment">#26-Ubuntu SMP Tue Feb 18 17:22:37 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux</span>
</code></pre>
<p>Here is what each part means in the above command:</p>
<ul>
<li><p><code>Linux</code>: The kernel name.</p>
</li>
<li><p><code>ip-172-31-90-178</code>: The network hostname of the system.</p>
</li>
<li><p><code>6.8.0-1024-aws</code>: The kernel version and AWS-specific build.</p>
</li>
<li><p><code>#26-Ubuntu</code>: The kernel build number.</p>
</li>
<li><p><code>SMP</code>: Symmetric Multi-Processing, indicating that the kernel is compiled for multiple processors.</p>
</li>
<li><p><code>Tue Feb 18 17:22:37 UTC 2025</code>: The date and time when the kernel was compiled.</p>
</li>
<li><p><code>x86_64 x86_64 x86_64</code>: The machine hardware name (architecture), processor type, and platform type, all indicating 64-bit x86 architecture.</p>
</li>
<li><p><code>GNU/Linux</code>: The operating system name.</p>
</li>
</ul>
<p>Based on this output, I’m running on an AWS EC2 instance with a 64-bit Ubuntu Linux distribution using a kernel that was specifically built for AWS infrastructure.</p>
<h3 id="heading-uname-r-and-uname-s-commands"><code>uname -r</code> and <code>uname -s</code> Commands</h3>
<p>The <code>uname -r</code> and <code>uname -s</code> commands specify the kernel version and OS type information:</p>
<pre><code class="lang-bash">uname -r
6.11.0-25-generic

uname -s
Linux
</code></pre>
<h3 id="heading-cat-etcos-release-command"><code>cat /etc/os-release</code> Command</h3>
<p>The <code>cat /etc/os-release</code> command provides distribution information:</p>
<pre><code class="lang-bash">cat /etc/os-release
PRETTY_NAME=<span class="hljs-string">"Ubuntu 24.04.2 LTS"</span>
NAME=<span class="hljs-string">"Ubuntu"</span>
VERSION_ID=<span class="hljs-string">"24.04"</span>
VERSION=<span class="hljs-string">"24.04.2 LTS (Noble Numbat)"</span>
VERSION_CODENAME=noble
ID=ubuntu
ID_LIKE=debian
HOME_URL=<span class="hljs-string">"https://www.ubuntu.com/"</span>
SUPPORT_URL=<span class="hljs-string">"https://help.ubuntu.com/"</span>
BUG_REPORT_URL=<span class="hljs-string">"https://bugs.launchpad.net/ubuntu/"</span>
PRIVACY_POLICY_URL=<span class="hljs-string">"https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"</span>
UBUNTU_CODENAME=noble
LOGO=ubuntu-logo
</code></pre>
<p>Here is what each part means in the above command:</p>
<ul>
<li><p><code>PRETTY_NAME="Ubuntu 24.04.2 LTS"</code>: The user-friendly name of the distribution including version and LTS (Long Term Support) designation.</p>
</li>
<li><p><code>NAME="Ubuntu"</code>: The name of the Linux distribution.</p>
</li>
<li><p><code>VERSION_ID="24.04"</code>: The version number of the Ubuntu release (Year/Month format).</p>
</li>
<li><p><code>VERSION="24.04.2 LTS (Noble Numbat)"</code>: The complete version information including:</p>
<p>  • <code>24.04</code>: Major version (released April 2024)</p>
<p>  • <code>.2</code>: Point release number</p>
<p>  • <code>LTS</code>: Long Term Support</p>
<p>  • <code>Noble Numbat</code>: The release codename</p>
</li>
<li><p><code>VERSION_CODENAME=noble</code>: The codename for this Ubuntu release ("Noble").</p>
</li>
<li><p><code>ID=ubuntu</code>: The machine-readable name of the operating system.</p>
</li>
<li><p><code>ID_LIKE=debian</code>: Indicates that Ubuntu is based on Debian Linux.</p>
</li>
<li><p><code>HOME_URL</code>, <code>SUPPORT_URL</code>, <code>BUG_REPORT_URL</code>, <code>PRIVACY_POLICY_URL</code> : Various official URLs for Ubuntu resources.</p>
</li>
<li><p><code>UBUNTU_CODENAME=noble</code>: Reiterates the codename of this Ubuntu release.</p>
</li>
<li><p><code>LOGO=ubuntu-logo</code>: Specifies the logo identifier for the distribution.</p>
</li>
</ul>
<p>This output shows that I’m running Ubuntu 24.04.2 LTS (codenamed "Noble Numbat"), which is a Long Term Support release of Ubuntu. Being an LTS version means it will receive security updates and support for an extended period (typically 5 years for Ubuntu LTS releases).</p>
<h3 id="heading-hostnamectl-command"><code>hostnamectl</code> Command</h3>
<p><code>hostnamectl</code> shows the hostname, OS, and kernel info:</p>
<pre><code class="lang-bash">hostnamectl
 Static hostname: ip-172-31-90-178
       Icon name: computer-vm
         Chassis: vm 🖴
      Machine ID: ec272830b6dca2da0d11e41b292cfc99
         Boot ID: dd12f48ff01b44a796991d99ce1bcfde
  Virtualization: xen
Operating System: Ubuntu 24.04.2 LTS              
          Kernel: Linux 6.8.0-1024-aws
    Architecture: x86-64
 Hardware Vendor: Xen
  Hardware Model: HVM domU
Firmware Version: 4.11.amazon
   Firmware Date: Thu 2006-08-24
    Firmware Age: 18y 9month 1w 2d
</code></pre>
<p>In the above command, here is what each part means:</p>
<ul>
<li><p><code>Static hostname: "ip-172-31-90-178"</code>: This is the permanent hostname of the system, stored in <code>/etc/hostname</code>.</p>
</li>
<li><p><code>Icon name: "computer-vm"</code>: A symbolic icon identifier for the system, used by some desktop environments.</p>
</li>
<li><p><code>Chassis: "vm"</code>: Indicates this is running in a virtual machine environment.</p>
</li>
<li><p><code>Machine ID: "ec272830b6dca2da0d11e41b292cfc99"</code>: A unique identifier for this system, stored in <code>/etc/machine-id</code>.</p>
</li>
<li><p><code>Boot ID: "dd12f48ff01b44a796991d99ce1bcfde"</code>: A unique identifier that changes with each system boot.</p>
</li>
<li><p><code>Virtualization: "xen"</code>: Shows that this system is running on Xen virtualization (common for AWS instances).</p>
</li>
<li><p><code>Operating System: "Ubuntu 24.04.2 LTS"</code>: The current OS distribution and version.</p>
</li>
<li><p><code>Kernel: "Linux 6.8.0-1024-aws"</code>: The current Linux kernel version, specifically an AWS-optimized kernel.</p>
</li>
<li><p><code>Architecture: "x86-64"</code>: The CPU architecture of the system.</p>
</li>
<li><p><code>Hardware Vendor: "Xen" Hardware Model: "HVM domU"</code>: Indicates this is a Xen HVM (Hardware Virtual Machine) domain user instance.</p>
</li>
<li><p>Firmware Details:</p>
<ul>
<li><p><code>Version: 4.11.amazon</code>: This is the version of the firmware/BIOS specifically customized for AWS environments.</p>
</li>
<li><p><code>Date: Thu 2006-08-24</code>: This is the release date of the firmware. The date might seem old (2006) but this is normal for AWS instances.</p>
</li>
<li><p><code>Age: 18y 9month 1w</code> : This shows how old the firmware is relative to the current date calculated from the firmware date (2006) to now (2025). While the firmware seems old, it is still maintained and secure.</p>
</li>
</ul>
</li>
</ul>
<p>This overall output shows that I’m running Ubuntu 24.04.2 LTS on an AWS EC2 instance using Xen virtualization. The system is using an AWS-optimized kernel and is configured as a HVM (Hardware Virtual Machine) instance.</p>
<h2 id="heading-how-to-get-your-cpu-information-in-linux">How to Get Your CPU Information in Linux</h2>
<h3 id="heading-lscpu-command"><code>lscpu</code> Command</h3>
<p><code>lscpu</code> shows CPU architecture, cores, threads, and virtualization information:</p>
<pre><code class="lang-bash">lscpu
Architecture:             x86_64
  CPU op-mode(s):         32-bit, 64-bit
  Address sizes:          46 bits physical, 48 bits virtual
  Byte Order:             Little Endian
CPU(s):                   1
  On-line CPU(s) list:    0
Vendor ID:                GenuineIntel
  Model name:             Intel(R) Xeon(R) CPU E5-2686 v4 @ 2
                          .30GHz
    CPU family:           6
    Model:                79
    Thread(s) per core:   1
    Core(s) per socket:   1
    Socket(s):            1
    Stepping:             1
    BogoMIPS:             4599.99
    Flags:                fpu vme de pse tsc msr pae mce cx8 
                          apic sep mtrr pge mca cmov pat pse3
                          6 clflush mmx fxsr sse sse2 ht sysc
                          all nx rdtscp lm constant_tsc rep_g
                          ood nopl xtopology cpuid tsc_known_
                          freq pni pclmulqdq ssse3 fma cx16 p
                          cid sse4_1 sse4_2 x2apic movbe popc
                          nt tsc_deadline_timer aes xsave avx
                           f16c rdrand hypervisor lahf_lm abm
                           pti fsgsbase bmi1 avx2 smep bmi2 e
                          rms invpcid xsaveopt
Virtualization features:  
  Hypervisor vendor:      Xen
  Virtualization <span class="hljs-built_in">type</span>:    full
Caches (sum of all):      
  L1d:                    32 KiB (1 instance)
  L1i:                    32 KiB (1 instance)
  L2:                     256 KiB (1 instance)
  L3:                     45 MiB (1 instance)
NUMA:                     
  NUMA node(s):           1
  NUMA node0 CPU(s):      0
Vulnerabilities:          
  Gather data sampling:   Not affected
  Itlb multihit:          KVM: Mitigation: VMX unsupported
  L1tf:                   Mitigation; PTE Inversion
  Mds:                    Vulnerable: Clear CPU buffers attem
                          pted, no microcode; SMT Host state 
                          unknown
  Meltdown:               Mitigation; PTI
  Mmio stale data:        Vulnerable: Clear CPU buffers attem
                          pted, no microcode; SMT Host state 
                          unknown
  Reg file data sampling: Not affected
  Retbleed:               Not affected
  Spec rstack overflow:   Not affected
  Spec store bypass:      Vulnerable
  Spectre v1:             Mitigation; usercopy/swapgs barrier
                          s and __user pointer sanitization
  Spectre v2:             Mitigation; Retpolines; STIBP disab
                          led; RSB filling; PBRSB-eIBRS Not a
                          ffected; BHI Retpoline
  Srbds:                  Not affected
  Tsx async abort:        Not affected
</code></pre>
<p>Here is a brief explanation of the output above:</p>
<p>1. Basic CPU Info</p>
<ul>
<li><p>Architecture: <code>x86_64</code> (64-bit)</p>
</li>
<li><p>CPU Model: Intel Xeon E5-2686 v4 (2.3 GHz)</p>
</li>
<li><p>Cores/Threads: 1 core, 1 thread (no Hyper-Threading)</p>
</li>
<li><p>Physical CPU (Socket): 1</p>
</li>
</ul>
<p>2. Performance &amp; Features</p>
<ul>
<li><p>Cache Sizes:</p>
<ul>
<li><p>L1: 32 KiB (data) + 32 KiB (instructions)</p>
</li>
<li><p>L2: 256 KiB</p>
</li>
<li><p>L3: 45 MiB (large, typical for Xeon)</p>
</li>
</ul>
</li>
<li><p>Flags: Supports AVX, AES, SSE4.1/4.2 (useful for encryption/vector ops).</p>
</li>
</ul>
<p>3. Virtualization</p>
<ul>
<li><p>Hypervisor: Running on Xen (full virtualization).</p>
</li>
<li><p>Virtualization Support: Yes (Intel VT-x).</p>
</li>
</ul>
<p>4. Security (Vulnerabilities)</p>
<ul>
<li><p>Meltdown/Spectre: Mostly mitigated (PTI, Retpolines).</p>
</li>
<li><p>MDS/MMIO: Vulnerable (no microcode fixes).</p>
</li>
<li><p>Spec Store Bypass: Vulnerable (no mitigation).</p>
</li>
</ul>
<p>5. NUMA (Memory)</p>
<ul>
<li>Single NUMA node (no multi-processor complexity).</li>
</ul>
<p>The output shows that my machine is a single-core Intel Xeon (in a virtualized/cloud environment) with large L3 cache but has some unpatched CPU vulnerabilities.</p>
<h3 id="heading-cat-proccpuinfo-command"><code>cat /proc/cpuinfo</code> Command</h3>
<p><code>cat /proc/cpuinfo</code> provides more in-depth details about the CPU:</p>
<pre><code class="lang-bash">cat /proc/cpuinfo 
processor    : 0
vendor_id    : GenuineIntel
cpu family    : 6
model        : 79
model name    : Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz
stepping    : 1
microcode    : 0xd000404
cpu MHz        : 2299.998
cache size    : 46080 KB
physical id    : 0
siblings    : 1
core id        : 0
cpu cores    : 1
apicid        : 0
initial apicid    : 0
fpu        : yes
fpu_exception    : yes
cpuid level    : 13
wp        : yes
flags        : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm pti fsgsbase bmi1 avx2 smep bmi2 erms invpcid xsaveopt
bugs        : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs itlb_multihit mmio_stale_data bhi
bogomips    : 4599.99
clflush size    : 64
cache_alignment    : 64
address sizes    : 46 bits physical, 48 bits virtual
power management:
</code></pre>
<h3 id="heading-nproc-command"><code>nproc</code> Command</h3>
<p><code>nproc</code> shows the core count:</p>
<pre><code class="lang-bash">nproc
1
</code></pre>
<p>The above command output shows there is one available processor.</p>
<h2 id="heading-how-to-get-your-memory-information-in-linux">How to Get Your Memory Information in Linux</h2>
<h3 id="heading-free-h-command"><code>free -h</code> Command</h3>
<p>You can use the <code>free -h</code> command to know the total/used/free RAM:</p>
<pre><code class="lang-bash">free -h
               total        used        free      shared  buff/cache   available
Mem:           957Mi       406Mi       218Mi       920Ki       522Mi       551Mi
Swap:             0B          0B          0B
</code></pre>
<p>Here is a breakdown of the output shared above:</p>
<ul>
<li><p><code>total</code>: The total amount of physical memory (RAM) or swap space available on the system.</p>
</li>
<li><p><code>used</code>: The amount of memory currently being used by applications and the system. Calculated as: <code>total - free - buffers - cache</code>.</p>
</li>
<li><p><code>free</code>: The amount of memory that is completely unused.</p>
</li>
<li><p><code>shared</code>: Memory that may be simultaneously accessed by multiple programs.</p>
</li>
<li><p><code>buff/cache</code>: Combines two types of memory:</p>
<ul>
<li><p>Buffers: Memory used for block device I/O buffering.</p>
</li>
<li><p>Cache: Memory used for file system page cache - This memory can be reclaimed when needed by applications.</p>
</li>
<li><p><code>available</code>: It includes the 'free' memory plus memory that can be reclaimed from <code>buff/cache</code>. This is the most important column for determining if you have enough memory.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-vmstat-command"><strong>vmstat</strong> Command</h3>
<p><code>vmstat</code> stands for Virtual Memory Statistics, a tool to monitor system performance. It provides information about memory usage, CPU activity, Processes, Disk I/O and Swap usage.</p>
<p>You can also use <code>vmstat</code> to extract live information. Here is how you can do that:</p>
<pre><code class="lang-bash">vmstat 1 5
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   <span class="hljs-keyword">in</span>   cs us sy id wa st gu
 1  0      0 238264  46120 489056    0    0     3     8   23    0  0  0 82  0 18  0
 0  0      0 238264  46120 489060    0    0     0     0  240  120  0  1 98  0  1  0
 0  0      0 238264  46120 489060    0    0     0     0  239  124  0  0 98  0  2  0
 0  0      0 238264  46120 489060    0    0     0     0  199  101  0  0 95  0  5  0
 0  0      0 238264  46120 489060    0    0     0     0   36   25  0  0 78  0 22  0
</code></pre>
<p>Here is what the above command is doing:</p>
<ol>
<li><p>Captures 5 snapshots of system performance.</p>
</li>
<li><p>Each snapshot is taken 1 second apart, giving near real-time insights.</p>
</li>
<li><p>Displays key metrics about:</p>
<ul>
<li><p>Memory usage (free, buffered, cached).</p>
</li>
<li><p>CPU activity (user, system, idle, waiting).</p>
</li>
<li><p>Processes (running, blocked).</p>
</li>
<li><p>Disk I/O (blocks read/written).</p>
</li>
<li><p>Swap usage (if swapping is happening).</p>
</li>
</ul>
</li>
</ol>
<p>Note that, you can replace the interval and number of snapshots accordingly.</p>
<p>Here’s a detailed breakdown of the output above:</p>
<ul>
<li><p><code>Procs</code>:</p>
<ul>
<li><p><code>r</code>: Number of processes waiting for run time.</p>
</li>
<li><p><code>b</code>: Number of processes in uninterruptible sleep</p>
</li>
</ul>
</li>
<li><p><code>Memory</code> (in KB):</p>
<ul>
<li><p><code>swpd</code>: Amount of virtual memory used</p>
</li>
<li><p><code>free</code>: Amount of idle memory</p>
</li>
<li><p><code>buff</code>: Memory used as buffers</p>
</li>
<li><p><code>cache</code>: Memory used as cache</p>
</li>
</ul>
</li>
<li><p><code>Swap</code>:</p>
<ul>
<li><p><code>si</code>: Memory swapped in from disk (KB/s)</p>
</li>
<li><p><code>so</code>: Memory swapped out to disk (KB/s)</p>
</li>
</ul>
</li>
<li><p><code>IO</code>:</p>
<ul>
<li><p><code>bi</code>: Blocks received from a block device (blocks/s)</p>
</li>
<li><p><code>bo</code>: Blocks sent to a block device (blocks/s)</p>
</li>
</ul>
</li>
<li><p><code>System</code>:</p>
<ul>
<li><p><code>in</code>: Number of interrupts per second</p>
</li>
<li><p><code>cs</code>: Number of context switches per second</p>
</li>
</ul>
</li>
<li><p><code>CPU</code> (percentages):</p>
<ol>
<li><p><code>us</code>: Time spent running user code</p>
</li>
<li><p><code>sy</code>: Time spent running system code</p>
</li>
<li><p><code>id</code>: Time spent idle</p>
</li>
<li><p><code>wa</code>: Time spent waiting for IO</p>
</li>
<li><p><code>st</code>: Time stolen from a virtual machine</p>
</li>
<li><p><code>gu</code>: Time running guest code (virtual CPU)</p>
</li>
</ol>
</li>
</ul>
<p>From the output, you can see that my system:</p>
<ul>
<li><p>Has very low CPU usage (high idle percentage)</p>
</li>
<li><p>Has no swap being used (<code>swpd = 0</code>)</p>
</li>
<li><p>Has about <code>99MB</code> free memory</p>
</li>
<li><p>Shows minimal IO activity</p>
</li>
<li><p>Is running in a virtualized environment (notice the <code>st</code> (stolen) time column has non-zero value</p>
</li>
</ul>
<p>The first line shows averages since the last reboot, while subsequent lines show the real-time statistics for each second.</p>
<h3 id="heading-cat-procmeminfo-command"><code>cat /proc/meminfo</code> Command</h3>
<p><code>cat /proc/meminfo</code> shows detailed memory stats:</p>
<pre><code class="lang-bash">cat /proc/meminfo
MemTotal:         980384 kB
MemFree:          245100 kB
MemAvailable:     585896 kB
Buffers:           46184 kB
Cached:           393672 kB
SwapCached:            0 kB
Active:           141404 kB
Inactive:         356376 kB
Active(anon):      47672 kB
Inactive(anon):    29300 kB
Active(file):      93732 kB
Inactive(file):   327076 kB
Unevictable:       36528 kB
Mlocked:           27152 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Zswap:                 0 kB
Zswapped:              0 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:         94488 kB
Mapped:            97936 kB
Shmem:               920 kB
KReclaimable:      95396 kB
Slab:             148672 kB
SReclaimable:      95396 kB
SUnreclaim:        53276 kB
KernelStack:        2444 kB
PageTables:         3224 kB
SecPageTables:         0 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:      490192 kB
Committed_AS:     508912 kB
VmallocTotal:   34359738367 kB
VmallocUsed:        9988 kB
VmallocChunk:          0 kB
Percpu:            14848 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
Unaccepted:            0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:       71680 kB
DirectMap2M:      976896 kB
</code></pre>
<p>Here is a detailed breakdown of the output shared above:</p>
<ul>
<li><p>Total Memory and Available Memory:</p>
<ul>
<li><p><code>MemTotal</code>: Total physical RAM available.</p>
</li>
<li><p><code>MemFree</code>: Completely unused memory.</p>
</li>
<li><p><code>MemAvailable</code>: Memory available for new applications.</p>
</li>
</ul>
</li>
<li><p>Memory Caches and Buffers:</p>
<ul>
<li><p><code>Buffers</code>: Memory used for block device I/O buffering.</p>
</li>
<li><p><code>Cached</code>: Memory used for file system cache.</p>
</li>
<li><p><code>SwapCached</code>: Memory pages stored in both RAM and swap.</p>
</li>
</ul>
</li>
<li><p>Active vs Inactive Memory:</p>
<ul>
<li><p><code>Active</code>: Recently used memory.</p>
</li>
<li><p><code>Inactive</code>: Less recently used memory.</p>
</li>
<li><p><code>Active(anon)</code>: Recently used anonymous memory.</p>
</li>
<li><p><code>Active(file)</code>: Recently used file-backed memory.</p>
</li>
</ul>
</li>
<li><p>Swap Information:</p>
<ul>
<li><p><code>SwapTotal</code>: Swap space configured.</p>
</li>
<li><p><code>SwapFree</code>: Swap space available.</p>
</li>
<li><p><code>Zswap</code>: Compressed swap in RAM.</p>
</li>
</ul>
</li>
<li><p>Other Important Metrics:</p>
<ul>
<li><p><code>Dirty</code>: Memory waiting to be written to disk.</p>
</li>
<li><p><code>Mapped</code>: Files mapped into memory.</p>
</li>
<li><p><code>Slab</code>: Kernel data structures cache.</p>
</li>
<li><p><code>CommitLimit</code>: Total memory available for allocation.</p>
</li>
<li><p><code>Committed_AS</code>: Total memory currently allocated.</p>
</li>
</ul>
</li>
</ul>
<p>A healthy memory usage is indicated by a good amount of available memory, active caching mechanisms in place and no memory pressure (no swap usage needed).</p>
<h2 id="heading-how-to-get-your-disk-amp-filesystem-information-in-linux">How to Get Your Disk &amp; Filesystem Information in Linux</h2>
<h3 id="heading-tree-d-l-1-command"><code>tree -d -L 1</code> Command</h3>
<p><code>tree -d -L 1</code> shows the file system details from the folder it is executed in. To find the complete file system details, run it from the root <code>/</code> folder:</p>
<pre><code class="lang-bash">tree -d -L 1
.
├── bin -&gt; usr/bin
├── bin.usr-is-merged
├── boot
├── dev
├── etc
├── home
├── lib -&gt; usr/lib
├── lib.usr-is-merged
├── lib64 -&gt; usr/lib64
├── lost+found
├── media
├── mnt
├── opt
├── proc
├── root
├── run
├── sbin -&gt; usr/sbin
├── sbin.usr-is-merged
├── snap
├── srv
├── sys
├── tmp
├── usr
└── var

25 directories
</code></pre>
<p>The command output of <code>tree -d -L 1</code> shows a directory tree structure with the following options:</p>
<ul>
<li><p><code>-d</code>: Shows only directories (ignores files)</p>
</li>
<li><p><code>-L 1</code>: Limits the depth of the tree to one level (only shows the immediate subdirectories)</p>
</li>
<li><p><code>df -h</code>: mounted filesystems and usage:</p>
<pre><code class="lang-bash">  df -h
  Filesystem      Size  Used Avail Use% Mounted on
  /dev/root        29G  2.6G   26G   9% /
  tmpfs           479M     0  479M   0% /dev/shm
  tmpfs           192M  908K  191M   1% /run
  tmpfs           5.0M     0  5.0M   0% /run/lock
  /dev/xvda16     881M  144M  676M  18% /boot
  /dev/xvda15     105M  6.1M   99M   6% /boot/efi
  tmpfs            96M   12K   96M   1% /run/user/1000
</code></pre>
<p>  The above output from the <code>df -h</code> command shows the following disk space usage information:</p>
<ul>
<li><p><code>Filesystem</code>: The name of the mounted filesystem/device.</p>
</li>
<li><p><code>Size</code>: Total size of the filesystem.</p>
</li>
<li><p><code>Used</code>: Amount of space used.</p>
</li>
<li><p><code>Avail</code>: Amount of space available.</p>
</li>
<li><p><code>Use%</code>: Percentage of space used.</p>
</li>
<li><p><code>Mounted on</code>: The mount point where the filesystem is attached</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-lsblk-command"><code>lsblk</code> Command</h3>
<p><code>lsblk</code> stands for ‘list block devices’ and shows information about all available block devices like hard drives, SSDs, and so on.</p>
<pre><code class="lang-bash">lsblk
NAME     MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
loop0      7:0    0 26.3M  1 loop /snap/amazon-ssm-agent/9881
loop1      7:1    0 73.9M  1 loop /snap/core22/1748
loop2      7:2    0 44.4M  1 loop /snap/snapd/23545
loop3      7:3    0 50.9M  1 loop /snap/snapd/24505
loop4      7:4    0 73.9M  1 loop /snap/core22/1963
loop5      7:5    0 27.2M  1 loop /snap/amazon-ssm-agent/11320
xvda     202:0    0   30G  0 disk 
├─xvda1  202:1    0   29G  0 part /
├─xvda14 202:14   0    4M  0 part 
├─xvda15 202:15   0  106M  0 part /boot/efi
└─xvda16 259:0    0  913M  0 part /boot
</code></pre>
<p>The output above shows the following details:</p>
<ul>
<li><p><code>NAME</code>: Device name.</p>
</li>
<li><p><code>MAJ:MIN</code>: Major and minor device numbers.</p>
</li>
<li><p><code>RM</code>: Removable flag (1 for removable, 0 for fixed).</p>
</li>
<li><p><code>SIZE</code>: Device size.</p>
</li>
<li><p><code>RO</code>: Read-only flag (1 for read-only, 0 for read-write).</p>
</li>
<li><p><code>TYPE</code>: Device type (disk, part for partition, loop for loop device).</p>
</li>
<li><p><code>MOUNTPOINTS</code>: Where the device is mounted.</p>
</li>
</ul>
<h3 id="heading-fdisk-l-command"><code>fdisk -l</code> Command</h3>
<p><code>fdisk -l</code> shows all disk devices and their partitions on your system:</p>
<pre><code class="lang-bash">Disk /dev/xvda: 30 GiB, 32212254720 bytes, 62914560 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel <span class="hljs-built_in">type</span>: gpt
Disk identifier: E3478E01-32E3-4FC2-8E79-1BCCDE89C2D7

Device        Start      End  Sectors  Size Type
/dev/xvda1  2099200 62914526 60815327   29G Linux filesystem
/dev/xvda14    2048    10239     8192    4M BIOS boot
/dev/xvda15   10240   227327   217088  106M EFI System
/dev/xvda16  227328  2097152  1869825  913M Linux extended boot
</code></pre>
<p>The above output shows the partition information for the the main system disk (<code>/dev/xvda</code>) which is 30 GiB in size and has four partitions:</p>
<ul>
<li><p><code>/dev/xvda1</code>: <code>29G</code> Linux filesystem (main system partition).</p>
</li>
<li><p><code>/dev/xvda14</code>: <code>4M</code> BIOS boot partition.</p>
</li>
<li><p><code>/dev/xvda15</code>: <code>106M</code> EFI System partition (for UEFI boot).</p>
</li>
<li><p><code>/dev/xvda16</code>: <code>913M</code> Linux extended boot partition.</p>
</li>
</ul>
<h3 id="heading-mount-command"><code>mount</code> Command</h3>
<p><code>mount</code> shows all currently mounted filesystems in the format: <code>device/source "on" mount_point "type" filesystem_type (mount_options)</code>, displaying where and how each filesystem is attached to your system's directory tree.</p>
<p>Here is an example line from the output of <code>mount</code>:</p>
<pre><code class="lang-bash">/dev/xvda1 on / <span class="hljs-built_in">type</span> ext4 (rw,relatime,discard,errors=remount-ro,commit=30)
</code></pre>
<p>Some common mount options you’ll see are:</p>
<ul>
<li><p><code>rw</code>: Read-write access.</p>
</li>
<li><p><code>ro</code>: Read-only access.</p>
</li>
<li><p><code>nosuid</code>: Disable SUID/SGID bits.</p>
</li>
<li><p><code>nodev</code>: Prevent device file interpretation.</p>
</li>
<li><p><code>noexec</code>: Prevent execution of binaries.</p>
</li>
<li><p><code>relatime</code>: Update access times relatively.</p>
</li>
</ul>
<h3 id="heading-du-sh-command"><code>du -sh *</code> Command</h3>
<p><code>du -sh *</code> provides a summary of the disk usage for each file and directory in the current directory (good for finding disk hogs):</p>
<pre><code class="lang-bash">du -sh *
4.0K    file1.txt
8.0K    file2.txt
12K     directory1
20K     directory2
</code></pre>
<h2 id="heading-how-to-get-your-hardware-information-in-linux">How to Get Your Hardware Information in Linux</h2>
<h3 id="heading-lshw-command"><code>lshw</code> Command</h3>
<p>The <code>lshw</code> command provides detailed information about the computer's hardware configuration. It can report:</p>
<ul>
<li><p>Memory configuration.</p>
</li>
<li><p>Firmware version.</p>
</li>
<li><p>Mainboard configuration.</p>
</li>
<li><p>CPU version and speed.</p>
</li>
<li><p>Cache configuration.</p>
</li>
<li><p>Bus speed and more.</p>
</li>
</ul>
<p>It's particularly useful for system administrators and users who need to gather detailed hardware information. The command can output information in various formats including HTML, XML, JSON, or plain text.</p>
<p>Here is a portion of the output from <code>lshw</code>:</p>
<pre><code class="lang-bash">*-pci
          description: Host bridge
          product: 440FX - 82441FX PMC [Natoma]
          vendor: Intel Corporation
          physical id: 100
          bus info: pci@0000:00:00.0
          version: 02
          width: 32 bits
          clock: 33MHz
        *-isa
             description: ISA bridge
             product: 82371SB PIIX3 ISA [Natoma/Triton II]
             vendor: Intel Corporation
             physical id: 1
             bus info: pci@0000:00:01.0
             version: 00
             width: 32 bits
             clock: 33MHz
             capabilities: isa bus_master
             configuration: latency=0
</code></pre>
<h3 id="heading-lspci-command"><code>lspci</code> Command</h3>
<p><code>lspci</code> displays information about all PCI (Peripheral Component Interconnect) buses and devices connected to your system.</p>
<pre><code class="lang-bash">lspci
00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 01)
00:02.0 VGA compatible controller: Cirrus Logic GD 5446
00:03.0 Unassigned class [ff80]: XenSource, Inc. Xen Platform Device (rev 01)
</code></pre>
<p>From the output, we can see that:</p>
<ul>
<li><p>Each line starts with a <code>bus:device.function</code> address (like "<code>00:00.0</code>")</p>
</li>
<li><p>Following the address is the device class and the specific hardware details:</p>
<ul>
<li><p>A Host bridge (<code>Intel 440FX)</code>, which manages communications between the CPU and other components.</p>
</li>
<li><p>An ISA bridge (<code>Intel PIIX3</code>), for legacy device support.</p>
</li>
<li><p>An IDE interface for storage devices.</p>
</li>
<li><p>An ACPI bridge for power management.</p>
</li>
<li><p>A VGA graphics controller (Cirrus Logic).</p>
</li>
<li><p>A Xen Platform Device (this suggests you're running in a Xen virtualized environment).</p>
</li>
</ul>
</li>
</ul>
<p>The command is particularly useful for:</p>
<ul>
<li><p>Troubleshooting hardware issues</p>
</li>
<li><p>Verifying hardware detection</p>
</li>
<li><p>Finding hardware details for driver installation</p>
</li>
<li><p>Checking system configuration</p>
</li>
</ul>
<h2 id="heading-how-to-get-your-network-interfaces-amp-status-information-in-linux">How to Get Your Network Interfaces &amp; Status Information in Linux</h2>
<h3 id="heading-ip-a-command"><code>ip a</code> Command</h3>
<p><code>ip a</code> displays information about all network interfaces on your system:</p>
<pre><code class="lang-bash">ip -a
1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt;
- This is the loopback interface (localhost)
- MTU (Maximum Transmission Unit) is 65536 bytes
- IP address: 127.0.0.1/8 (IPv4)
- IPv6 address: ::1/128

2. Network Interface (enX0):
enX0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt;
- This is your main network interface
- MTU is 9001 bytes
- MAC address (link/ether): 12:16:a6:d3:b3:61
- IPv4 address: 172.31.90.178/20
- IPv6 address: fe80::1016:a6ff:fed3:b361/64 (Link-local)
</code></pre>
<p>Here are the key elements in the output:</p>
<ul>
<li><p>Interface state (UP/DOWN).</p>
</li>
<li><p>MAC address (link/ether).</p>
</li>
<li><p>IPv4 and IPv6 addresses.</p>
</li>
<li><p>Network scope (host, global, link).</p>
</li>
<li><p>Address validity lifetime (valid_lft).</p>
</li>
<li><p>Broadcast address (brd).</p>
</li>
</ul>
<h3 id="heading-ip-r-command"><code>ip r</code> Command</h3>
<p><code>ip r</code> shows the system’s routing table:</p>
<pre><code class="lang-bash">ip r
default via 172.31.80.1 dev enX0 proto dhcp src 172.31.90.178 metric 100 
172.31.0.2 via 172.31.80.1 dev enX0 proto dhcp src 172.31.90.178 metric 100 
172.31.80.0/20 dev enX0 proto kernel scope link src 172.31.90.178 metric 100 
172.31.80.1 dev enX0 proto dhcp scope link src 172.31.90.178 metric 100
</code></pre>
<p>The above <code>ip r</code> output shows my system's routing table with the following routes:</p>
<ul>
<li><p>Default Route (Gateway):</p>
<ul>
<li><p>Default via <code>172.31.80.1</code>: All traffic not matching other rules goes through this gateway.</p>
</li>
<li><p>Using interface <code>enX0</code>.</p>
</li>
<li><p>Configured via DHCP.</p>
</li>
<li><p>Source IP: <code>172.31.90.178</code>.</p>
</li>
</ul>
</li>
<li><p>Local Network:</p>
<ul>
<li><p><code>172.31.80.0/20</code>: Local subnet (covers IPs from <code>172.31.80.0</code> to <code>172.31.95.255</code>)</p>
</li>
<li><p>Directly connected to <code>enX0</code> interface</p>
</li>
<li><p>Kernel-managed route (proto kernel)</p>
</li>
<li><p>For packets originating from <code>172.31.90.178</code></p>
</li>
</ul>
</li>
<li><p>DHCP Route:</p>
<ul>
<li><p>Direct route to DHCP server (<code>172.31.80.1</code>)</p>
</li>
<li><p>Via interface <code>enX0</code></p>
</li>
</ul>
</li>
</ul>
<p>All routes have a metric of 100, which determines route priority (lower values are preferred).</p>
<p><code>netstat -tuln</code> shows active listening ports:</p>
<pre><code class="lang-bash">netstat -tuln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.54:53           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN     
tcp6       0      0 :::80                   :::*                    LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
udp        0      0 127.0.0.54:53           0.0.0.0:*                          
udp        0      0 127.0.0.53:53           0.0.0.0:*                          
udp        0      0 172.31.90.178:68        0.0.0.0:*                          
udp        0      0 127.0.0.1:323           0.0.0.0:*                          
udp6       0      0 ::1:323                 :::*
</code></pre>
<h2 id="heading-how-to-get-your-software-amp-services-information-in-linux">How to Get Your Software &amp; Services Information in Linux</h2>
<h3 id="heading-installed-packages">Installed packages</h3>
<p>You can check installed packages with <code>dpkg -l</code>, <code>apt list --installed</code> (Debian/Ubuntu). Here is a snippet from the output:</p>
<pre><code class="lang-bash">vim-common/noble-updates,noble-security,now 2:9.1.0016-1ubuntu7.8 all [installed,automatic]
vim-runtime/noble-updates,noble-security,now 2:9.1.0016-1ubuntu7.8 all [installed,automatic]
vim-tiny/noble-updates,noble-security,now 2:9.1.0016-1ubuntu7.8 amd64 [installed,automatic]
vim/noble-updates,noble-security,now 2:9.1.0016-1ubuntu7.8 amd64 [installed,automatic]
</code></pre>
<h3 id="heading-service-status">Service status</h3>
<p><code>systemctl list-units --type=service</code> lists the services. You can also use <code>systemctl status &lt;service&gt;</code> and replace <code>&lt;service&gt;</code> with the one you want.</p>
<p>Here’s the output for <code>cron.service</code>:</p>
<pre><code class="lang-bash">systemctl status cron.service
● cron.service - Regular background program processing daemon
     Loaded: loaded (/usr/lib/systemd/system/cron.service; enabled; preset: enabled)
     Active: active (running) since Wed 2025-05-14 19:46:58 UTC; 2 weeks 5 days ago
       Docs: man:cron(8)
   Main PID: 625 (cron)
      Tasks: 1 (<span class="hljs-built_in">limit</span>: 1129)
     Memory: 1.7M (peak: 4.7M)
        CPU: 20.890s
     CGroup: /system.slice/cron.service
             └─625 /usr/sbin/cron -f -P

Jun 03 09:25:01 ip-172-31-90-178 CRON[121748]: pam_unix(cron:session): session closed <span class="hljs-keyword">for</span> user root
Jun 03 09:35:01 ip-172-31-90-178 CRON[121817]: pam_unix(cron:session): session opened <span class="hljs-keyword">for</span> user root(uid=0) by root(uid=0)
Jun 03 09:35:01 ip-172-31-90-178 CRON[121818]: (root) CMD (<span class="hljs-built_in">command</span> -v debian-sa1 &gt; /dev/null &amp;&amp; debian-sa1 1 1)
Jun 03 09:35:01 ip-172-31-90-178 CRON[121817]: pam_unix(cron:session): session closed <span class="hljs-keyword">for</span> user root
Jun 03 09:45:01 ip-172-31-90-178 CRON[122050]: pam_unix(cron:session): session opened <span class="hljs-keyword">for</span> user root(uid=0) by root(uid=0)
Jun 03 09:45:01 ip-172-31-90-178 CRON[122051]: (root) CMD (<span class="hljs-built_in">command</span> -v debian-sa1 &gt; /dev/null &amp;&amp; debian-sa1 1 1)
Jun 03 09:45:01 ip-172-31-90-178 CRON[122050]: pam_unix(cron:session): session closed <span class="hljs-keyword">for</span> user root
Jun 03 09:55:01 ip-172-31-90-178 CRON[122318]: pam_unix(cron:session): session opened <span class="hljs-keyword">for</span> user root(uid=0) by root(uid=0)
Jun 03 09:55:01 ip-172-31-90-178 CRON[122319]: (root) CMD (<span class="hljs-built_in">command</span> -v debian-sa1 &gt; /dev/null &amp;&amp; debian-sa1 1 1)
Jun 03 09:55:01 ip-172-31-90-178 CRON[122318]: pam_unix(cron:session): session closed <span class="hljs-keyword">for</span> user root
lines 5-21/21 (END)
</code></pre>
<h3 id="heading-processes"><strong>Processes</strong></h3>
<p><code>ps aux</code> shows all processes with their respective status:</p>
<pre><code class="lang-bash">ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  1.4  22556 13952 ?        Ss   May14   0:35 /usr/lib/systemd/systemd --system --deserialize=63
root           2  0.0  0.0      0     0 ?        S    May14   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        S    May14   0:00 [pool_workqueue_release]
root           4  0.0  0.0      0     0 ?        I&lt;   May14   0:00 [kworker/R-rcu_g]
root           5  0.0  0.0      0     0 ?        I&lt;   May14   0:00 [kworker/R-rcu_p]
root           6  0.0  0.0      0     0 ?        I&lt;   May14   0:00 [kworker/R-slub_]
.
.
.
</code></pre>
<p>Here's an explanation of each column in the <code>ps aux</code> output:</p>
<ul>
<li><p><code>USER</code>: The owner of the process</p>
</li>
<li><p><code>PID</code>: Process ID number</p>
</li>
<li><p><code>%CPU</code>: CPU usage percentage</p>
</li>
<li><p><code>%MEM</code>: Memory usage percentage</p>
</li>
<li><p><code>VSZ</code>: Virtual Memory Size in kilobytes (total program size)</p>
</li>
<li><p><code>RSS</code>: Resident Set Size in kilobytes (actual memory used)</p>
</li>
<li><p><code>TTY</code>: Terminal associated with the process ('?' means no terminal)</p>
</li>
<li><p><code>STAT</code>: Process state code:</p>
<ul>
<li><p><code>S</code>: Sleeping</p>
</li>
<li><p><code>R</code>: Running</p>
</li>
<li><p><code>I</code>: Idle</p>
</li>
<li><p><code>Z</code>: Zombie</p>
</li>
<li><p><code>T</code>: Stopped</p>
</li>
<li><p><code>s</code>: Session leader</p>
</li>
<li><p><code>&lt;</code>: High priority</p>
</li>
<li><p><code>N</code>: Low priority</p>
</li>
</ul>
</li>
<li><p><code>START</code>: Time when the process started</p>
</li>
<li><p><code>TIME</code>: Cumulative CPU time used</p>
</li>
<li><p><code>COMMAND</code>: The command with all its arguments</p>
</li>
</ul>
<h3 id="heading-top-and-htop-commands"><code>top</code> and <code>htop</code> Commands</h3>
<p><code>top</code> or <code>htop</code> can be used for live usage overview, and for showing a dynamic view of system performance and running processes. Here's what it displays:</p>
<ul>
<li><p>System Overview:</p>
<ul>
<li><p>System uptime and number of logged-in users.</p>
</li>
<li><p>Load average values for the last 1, 5, and 15 minutes.</p>
</li>
<li><p>Total number of processes and their states (running, sleeping, stopped, zombie)</p>
</li>
</ul>
</li>
<li><p>Resource Usage:</p>
<ul>
<li><p>CPU usage breakdown (user, system, idle, etc.).</p>
</li>
<li><p>Memory usage (total, free, used, cached).</p>
</li>
<li><p>Swap space usage</p>
</li>
<li><p>Process List:Shows a sorted list of running processes (by default sorted by CPU usage)For each process, displays:</p>
<ul>
<li><p>Process ID (PID).</p>
</li>
<li><p>User who owns the process.</p>
</li>
<li><p>CPU and memory usage.</p>
</li>
<li><p>Process priority and nice value.</p>
</li>
<li><p>Memory usage details (virtual, resident, shared).</p>
</li>
<li><p>Process status.</p>
</li>
<li><p>Running time.</p>
</li>
<li><p>Command name.</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-bash">    top - 10:04:25 up 19 days, 14:17,  1 user,  load average: 0.00, 0.00, 0.00
    Tasks: 104 total,   1 running, 103 sleeping,   0 stopped,   0 zombie
    %Cpu(s):  0.0 us,  0.0 sy,  0.0 ni, 88.0 id,  0.0 wa,  0.0 hi,  0.0 si, 12.0 st 
    MiB Mem :    957.4 total,    247.3 free,    366.1 used,    533.7 buff/cache     
    MiB Swap:      0.0 total,      0.0 free,      0.0 used.    591.3 avail Mem 

        PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                              
          1 root      20   0   22556  13952   9728 S   0.0   1.4   0:35.08 systemd                                              
          2 root      20   0       0      0      0 S   0.0   0.0   0:00.16 kthreadd                                             
          3 root      20   0       0      0      0 S   0.0   0.0   0:00.00 pool_workqueue_release                               
          4 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/R-rcu_g                                      
          5 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/R-rcu_p                                      
          6 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/R-slub_                                      
          7 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/R-netns                                      
         10 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/0:0H-events_highpri                          
         12 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/R-mm_pe                                      
         13 root      20   0       0      0      0 I   0.0   0.0   0:00.00 rcu_tasks_rude_kthread                               
         14 root      20   0       0      0      0 I   0.0   0.0   0:00.00 rcu_tasks_trace_kthread
</code></pre>
<p>    The top command updates this information regularly (by default every 3 seconds) and is commonly used for:</p>
<ul>
<li><p>Monitoring system performance</p>
</li>
<li><p>Identifying resource-intensive processes</p>
</li>
<li><p>Troubleshooting system slowdowns</p>
</li>
<li><p>Getting a quick overview of system health</p>
<p>  You can also interact with top while it's running using various keyboard commands (like 'k' to kill a process, '1' to see cpu cores, etc.).</p>
</li>
</ul>
<h2 id="heading-how-to-get-your-logs-amp-dmesg-in-formation-in-linux">How to Get Your Logs &amp; Dmesg In formation in Linux</h2>
<p>Based on the system configuration, a number of logs are generated. These can be audit logs, system logs, cron logs, and so on. They all carry useful information. Here are some commands that you can use to view logs:</p>
<ul>
<li><p><code>dmesg | less</code>: Kernel ring buffer (hardware issues, boot messages)</p>
</li>
<li><p><code>journalctl -xe</code>: Recent critical logs (systemd systems)</p>
</li>
<li><p><code>/var/log/syslog</code> or <code>/var/log/messages</code>: General system logs</p>
</li>
</ul>
<h2 id="heading-how-to-get-your-securityuser-audit-information-in-linux">How to Get Your Security/User Audit Information in Linux</h2>
<p><code>whoami</code> shows the current user’s username.</p>
<pre><code class="lang-bash">whoami
ubuntu
</code></pre>
<p><code>id</code> shows detailed information about a user's identity on the system.</p>
<pre><code class="lang-bash">id
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),24(cdrom),27(sudo),30(dip),105(lxd)
</code></pre>
<p>Let's break down the output:</p>
<ul>
<li><p>User ID (uid): <code>uid=1000(ubuntu)</code> means the user ID is 1000, with username "ubuntu"</p>
</li>
<li><p>Primary Group ID (gid): <code>gid=1000(ubuntu)</code> means the primary group ID is 1000, named "ubuntu"</p>
</li>
<li><p>Supplementary Groups (groups): The user belong to the following groups:</p>
<ul>
<li><p><code>ubuntu (1000)</code>: Your primary group.</p>
</li>
<li><p><code>adm (4)</code>: For system monitoring tasks.</p>
</li>
<li><p><code>cdrom (24)</code>: For accessing CD-ROM devices.</p>
</li>
<li><p><code>sudo (27)</code>: Allows you to execute commands with superuser privileges.</p>
</li>
<li><p><code>dip (30)</code>: For managing dial-up connections.</p>
</li>
<li><p><code>lxd (105)</code>: For managing LXD containers.</p>
</li>
</ul>
</li>
</ul>
<p>The <code>id</code> command is useful for checking user and group IDs, verifying group memberships, troubleshooting permissions issues and confirming sudo access.</p>
<p><code>who</code> displays information about users currently logged into the system:</p>
<pre><code class="lang-bash">who
ubuntu   pts/0        2025-06-03 08:45 (39.43.159.5)
</code></pre>
<p>The output breakdown is shown below:</p>
<ul>
<li><p>Username: "<code>ubuntu</code>"</p>
</li>
<li><p>Terminal: "<code>pts/0</code>" (pseudo-terminal)</p>
</li>
<li><p>Login time: "<code>2025-06-03 08:45"</code></p>
</li>
<li><p>Remote host: "<code>(39.43.159.5)</code>" - the IP address from where the connection was made</p>
</li>
<li><p><code>w</code>- shows who is logged in and what they are doing:</p>
</li>
</ul>
<pre><code class="lang-bash">w
 10:21:46 up 19 days, 14:35,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU  WHAT
ubuntu   pts/0    39.43.159.5      08:45   44:56   0.00s  0.02s sshd: ubuntu [priv]
</code></pre>
<p>Here is the result breakdown:</p>
<p>First line:</p>
<ul>
<li><p><code>10:21:46</code>: Current system time</p>
</li>
<li><p><code>up 19 days, 14:35</code>: System uptime (how long the system has been running)</p>
</li>
<li><p><code>1 user</code>: Number of users currently logged in</p>
</li>
<li><p><code>load average: 0.24, 0.05, 0.02</code>: System load averages for the past 1, 5, and 15 minutes</p>
<ul>
<li><p>Numbers below 1.0 indicate low system load</p>
</li>
<li><p>Higher numbers indicate more system load/stress</p>
</li>
</ul>
</li>
</ul>
<p>Second line shows the column headers for the user information below:</p>
<ul>
<li><p><code>USER</code>: Username.</p>
</li>
<li><p><code>TTY</code>: Terminal device being used.</p>
</li>
<li><p><code>FROM</code>: Remote host from where the user is connected.</p>
</li>
<li><p><code>LOGIN@</code>: Time when the user logged in.</p>
</li>
<li><p><code>IDLE</code>: Time since the user's last activity.</p>
</li>
<li><p><code>JCPU</code>: CPU time used by all processes attached to the tty.</p>
</li>
<li><p><code>PCPU</code>: CPU time used by the current process.</p>
</li>
<li><p><code>WHAT</code>: Current process/command being run.</p>
</li>
</ul>
<p><code>last</code> shows a history of user logins and system reboots:</p>
<pre><code class="lang-bash">last
ubuntu   pts/1        39.43.159.5      Tue Jun  3 10:15 - 10:17  (00:02)
ubuntu   pts/0        39.43.159.5      Tue Jun  3 08:45   still logged <span class="hljs-keyword">in</span>
ubuntu   pts/0        39.43.159.5      Tue Jun  3 05:23 - 08:29  (03:06)
ubuntu   pts/0        39.43.159.5      Sun Jun  1 06:32 - 12:24  (05:52)
ubuntu   pts/0        39.43.159.5      Thu May 22 05:39 - 05:58  (00:18)
ubuntu   pts/0        139.135.32.93    Wed May 21 14:45 - 14:47  (00:01)
ubuntu   pts/0        139.135.32.93    Wed May 21 11:58 - 13:49  (01:51)
ubuntu   pts/0        39.43.159.5      Wed May 21 05:05 - 05:12  (00:06)
ubuntu   pts/0        39.43.159.5      Tue May 20 18:41 - 21:45  (03:04)
ubuntu   pts/0        39.43.159.5      Thu May 15 06:12 - 06:12  (00:00)
ubuntu   pts/0        39.43.159.5      Thu May 15 06:05 - 06:12  (00:07)
ubuntu   pts/0        18.206.107.27    Wed May 14 20:06 - 20:08  (00:01)
ubuntu   pts/0        182.185.185.39   Wed May 14 19:48 - 19:50  (00:01)
reboot   system boot  6.8.0-1024-aws   Wed May 14 19:46   still running

wtmp begins Wed May 14 19:46:47 2025
</code></pre>
<p>Each line shows:</p>
<ul>
<li><p>Username (in this case, all logins are from 'ubuntu' user).</p>
</li>
<li><p>Terminal device (<code>pts/0</code> indicates a pseudo-terminal, typically used for SSH connections).</p>
</li>
<li><p>Remote host IP address (where the connection came from).</p>
</li>
<li><p>Login time and date.</p>
</li>
<li><p>Logout time or status.</p>
</li>
<li><p>Session duration in parentheses.</p>
</li>
</ul>
<p><code>sudo -l</code> shows what the current user can do with sudo.</p>
<pre><code class="lang-bash">sudo -l
Matching Defaults entries <span class="hljs-keyword">for</span> ubuntu on ip-172-31-90-178:
    env_reset, mail_badpass, secure_path=/usr/<span class="hljs-built_in">local</span>/sbin\:/usr/<span class="hljs-built_in">local</span>/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
    use_pty

User ubuntu may run the following commands on ip-172-31-90-178:
    (ALL : ALL) ALL
    (ALL) NOPASSWD: ALL
</code></pre>
<p>This output indicates that the 'ubuntu' user has:</p>
<ul>
<li><p>Full sudo access (can execute any command)</p>
</li>
<li><p>No password requirement for sudo commands</p>
</li>
<li><p>Complete administrative privileges on the system</p>
</li>
</ul>
<h2 id="heading-visually-appealing-commands">Visually Appealing Commands</h2>
<p>In this section you’ll learn about two commands that display the information we have seen before in a presentable and aesthetic form.</p>
<p><code>neofetch</code> - displays system info along with the distribution logo:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748945743174/9cef1af7-fce8-4657-ad26-7d75b5755dd1.png" alt="Terminal output of the neofetch command displaying Ubuntu system information, including OS, kernel, uptime, CPU, GPU, memory, and a colorful ASCII logo" class="image--center mx-auto" width="1026" height="749" loading="lazy"></p>
<p><code>btop</code> displays dynamic stats with different modes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1748945510465/8c8c200c-bb1a-4123-8db7-c30bb6a1c9bf.gif" alt="A realtime snapshot of the btop system monitor showing real-time CPU, memory, disk, and network usage in a terminal. Colorful graphs display performance metrics for processes, temperatures, and uptime" class="image--center mx-auto" width="1920" height="956" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thank you for reading the article until the end. If you found it helpful, consider sharing it with others.</p>
<p><strong>Stay Connected and Continue Your Learning Journey!</strong></p>
<p>I read every message, come say hi 👋</p>
<ol>
<li><p><strong>Connect with me on</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://www.linkedin.com/in/zaira-hira/">LinkedIn</a>: I share content related to Linux, Cyber security and DevOps. Leave a recommendation on LinkedIn and endorse me on relevant skills.</p>
</li>
<li><p><a target="_blank" href="https://discord.gg/9zfbjEDs">Discord</a> community: Hang around with other devs or share your accomplishments.</p>
</li>
<li><p><a target="_blank" href="https://twitter.com/hira_zaira">X</a>: I share pre-launch updates and some behind the scenes.</p>
</li>
</ul>
</li>
<li><p><strong>Get access to exclusive content</strong>: For one-on-one help and exclusive content go <a target="_blank" href="https://buymeacoffee.com/zairah/extras">here</a>.</p>
</li>
</ol>
<p>My <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">articles</a> are part of my mission to increase accessibility to quality content for everyone. Each piece takes a lot of time and effort to write. This article will be free, forever. If you've enjoyed my work and want to keep me motivated, consider <a target="_blank" href="https://buymeacoffee.com/zairah">buying me a coffee</a>.</p>
<p>Thank you once again and happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Linux for Beginners: From Basics to Advanced Techniques [Full Book] ]]>
                </title>
                <description>
                    <![CDATA[ Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux. While empowering you in your current role, lear... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-linux-for-beginners-book-basic-to-advanced/</link>
                <guid isPermaLink="false">66912d3051ed9fa23c06c654</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jul 2024 13:18:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720790242560/764782a4-1bf3-45a5-857c-7fe3921bfb08.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux.</p>
<p>While empowering you in your current role, learning Linux can also help you transition into other tech careers like DevOps, Cybersecurity, and Cloud Computing.</p>
<p>In this handbook, you'll learn the basics of the Linux command line, and then transition to more advanced topics like shell scripting and system administration. Whether you are new to Linux or have been using it for years, this book has something for you.</p>
<p>Important Note: All examples in this book are demonstrated in Ubuntu 22.04.2 LTS (Jammy Jellyfish). Most command line tools are more or less the same in other distributions. However, some GUI applications and commands may differ if you are working on another Linux distribution.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-11-getting-started-with-linux">1.1. Getting Started with Linux</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-22-command-structure">2.2. Command Structure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-43-managing-files-and-directories">4.3. Managing Files and Directories</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-52-mastering-nano">5.2. Mastering Nano</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-6-bash-scripting">Part 6: Bash Scripting</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-71-packages-and-package-management">7.1. Packages and Package Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-81-user-management">8.1. User Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-87-linux-networking-basics">8.7. Linux Networking Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-810-diagnosing-hardware-problems">8.10 Diagnosing Hardware Problems</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</h2>
<h3 id="heading-11-getting-started-with-linux">1.1. Getting Started with Linux</h3>
<h4 id="heading-what-is-linux">What is Linux?</h4>
<p>Linux is an open-source operating system that is based on the Unix operating system. It was created by Linus Torvalds in 1991.</p>
<p>Open source means that the source code of the operating system is available to the public. This allows anyone to modify the original code, customise it, and distribute the new operating system to potential users.</p>
<h4 id="heading-why-should-you-learn-about-linux">Why should you learn about Linux?</h4>
<p>In today's data center landscape, Linux and Microsoft Windows stand out as the primary contenders, with Linux having a major share.</p>
<p>Here are several compelling reasons to learn Linux:</p>
<ul>
<li><p>Given the prevalence of Linux hosting, there is a high chance that your application will be hosted on Linux. So learning Linux as a developer becomes increasingly valuable.</p>
</li>
<li><p>With cloud computing becoming the norm, chances are high that your cloud instances will rely on Linux.</p>
</li>
<li><p>Linux serves as the foundation for many operating systems for the Internet of Things (IoT) and mobile applications.</p>
</li>
<li><p>In IT, there are many opportunities for those skilled in Linux.</p>
</li>
</ul>
<h4 id="heading-what-does-it-mean-that-linux-is-an-open-source-operating-system">What does it mean that Linux is an open-source operating system?</h4>
<p>First, what is open source? Open source software is software whose source code is freely accessible, allowing anyone to utilize, modify, and distribute it.</p>
<p>Whenever source code is created, it is automatically considered copyrighted, and its distribution is governed by the copyright holder through software licenses.</p>
<p>In contrast to open source, proprietary or closed-source software restricts access to its source code. Only the creators can view, modify, or distribute it.</p>
<p>Linux is primarily open source, which means that its source code is freely available. Anyone can view, modify, and distribute it. Developers from anywhere in the world can contribute to its improvement. This lays the foundation of collaboration which is an important aspect of open source software.</p>
<p>This collaborative approach has led to the widespread adoption of Linux across servers, desktops, embedded systems, and mobile devices.</p>
<p>The most interesting aspect of Linux being open source is that anyone can tailor the operating system to their specific needs without being restricted by proprietary limitations.</p>
<p>Chrome OS used by Chromebooks is based on Linux. Android, that powers many smartphones globally, is also based on Linux.</p>
<p><strong>What is a Linux Kernel?</strong></p>
<p>The kernel is the central component of an operating system that manages the computer and its hardware operations. It handles memory operations and CPU time.</p>
<p>The kernel acts as a bridge between applications and the hardware-level data processing using inter-process communication and system calls.</p>
<p>The kernel loads into memory first when an operating system starts and remains there until the system shuts down. It is responsible for tasks like disk management, task management, and memory management.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719844849011/f4bb226e-f319-4cb5-bfc9-c1a80401123e.png" alt="Linux Kernel Layout showing interaction of kernal with applications and OS" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If you are curious about what the Linux kernel looks like, <a target="_blank" href="https://github.com/torvalds/linux">here</a> is the GitHub link.</p>
<h4 id="heading-what-is-a-linux-distribution">What is a Linux distribution?</h4>
<p>By this point, you know that you can re-use the Linux kernel code, modify it, and create a new kernel. You can further combine different utilities and software to create a completely new operating system.</p>
<p>A Linux distribution or distro is a version of the Linux operating system that includes the Linux kernel, system utilities, and other software. Being open source, a Linux distribution is a collaborative effort involving multiple independent open-source development communities.</p>
<p><strong>What does it mean that a distribution is derived?</strong> When you say that a distribution is "derived" from another, the newer distro is built upon the base or foundation of the original distro. This derivation can include using the same package management system (more on this later), kernel version, and sometimes the same configuration tools.</p>
<p>Today, there are thousands of Linux distributions to choose from, offering differing goals and criteria for selecting and supporting the software provided by their distribution.</p>
<p>Distributions vary from one to the other, but they generally have several common characteristics:</p>
<ul>
<li><p>A distribution consists of a Linux kernel.</p>
</li>
<li><p>It supports user space programs.</p>
</li>
<li><p>A distribution may be small and single-purpose or include thousands of open-source programs.</p>
</li>
<li><p>Some means of installing and updating the distribution and its components should be provided.</p>
</li>
</ul>
<p>If you view the <a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/1/1b/Linux_Distribution_Timeline.svg">Linux Distributions Timeline</a>, you'll see two major distros: Slackware and Debian. Several distributions are derived from them. For example, Ubuntu and Kali are derived from Debian.</p>
<p><strong>What are the advantages of derivation?</strong> There are various advantages of derivation. Derived distributions can leverage the stability, security, and large software repositories of the parent distribution.</p>
<p>When building on an existing foundation, developers can drive their focus and effort entirely on the specialized features of the new distribution. Users of derived distributions can benefit from the documentation, community support, and resources already available for the parent distribution.</p>
<p>Some popular Linux distributions are:</p>
<ol>
<li><p><strong>Ubuntu</strong>: One of the most widely used and popular Linux distributions. It is user-friendly and recommended for beginners. <a target="_blank" href="https://ubuntu.com/">Learn more about Ubuntu here</a>.</p>
</li>
<li><p><strong>Linux Mint</strong>: Based on Ubuntu, Linux Mint provides a user-friendly experience with a focus on multimedia support. <a target="_blank" href="https://linuxmint.com/">Learn more about Linux Mint here</a>.</p>
</li>
<li><p><strong>Arch Linux</strong>: Popular among experienced users, Arch is a lightweight and flexible distribution aimed at users who prefer a DIY approach. <a target="_blank" href="https://www.archlinux.org/">Learn more about Arch Linux here</a>.</p>
</li>
<li><p><strong>Manjaro</strong>: Based on Arch Linux, Manjaro provides a user-friendly experience with pre-installed software and easy system management tools. <a target="_blank" href="https://manjaro.org/">Learn more about Manjaro here</a>.</p>
</li>
<li><p><strong>Kali Linux</strong>: Kali Linux provides a comprehensive suite of security tools and is mostly focused on cybersecurity and hacking. <a target="_blank" href="https://www.kali.org/">Learn more about Kali Linux here</a>.</p>
</li>
</ol>
<h4 id="heading-how-to-install-and-access-linux">How to install and access Linux</h4>
<p>The best way to learn is to apply the concepts as you go. In this section, we'll learn how to install Linux on your machine so you can follow along. You'll also learn how to access Linux on a Windows machine.</p>
<p>I recommend that you follow any one of the methods mentioned in this section to get access to Linux so you may follow along.</p>
<h5 id="heading-install-linux-as-the-primary-os">Install Linux as the primary OS</h5>
<p>Installing Linux as the primary OS is the most efficient way to use Linux, as you can use the full power of your machine.</p>
<p>In this section, you will learn how to install Ubuntu, which is one of the most popular Linux distributions. I have left out other distributions for now, as I want to keep things simple. You can always explore other distributions once you are comfortable with Ubuntu.</p>
<ul>
<li><p><strong>Step 1 – Download the Ubuntu iso:</strong> Go to the official <a target="_blank" href="https://ubuntu.com/download/desktop">website</a> and download the iso file. Make sure to select a stable release that is labeled "LTS". LTS stands for Long Term Support which means you can get free security and maintenance updates for a long time (usually 5 years).</p>
</li>
<li><p><strong>Step 2 – Create a bootable pendrive:</strong> There are a number of softwares that can create a bootable pendrive. I recommend using Rufus, as it is quite easy to use. You can download it from <a target="_blank" href="https://rufus.ie/">here</a>.</p>
</li>
<li><p><strong>Step 3 – Boot from the pendrive:</strong> Once your bootable pendrive is ready, insert it and boot from the pendrive. The boot menu depends on your laptop. You can google the boot menu for your laptop model.</p>
</li>
<li><p><strong>Step 4 – Follow the prompts.</strong> Once, the boot process starts, select <code>try or install ubuntu</code>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304227675/5b706f94-7368-47ca-a4d6-d55a0d92eff9.png" alt="Screen prompt to either try or install Ubuntu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>  The process will take some time. Once the GUI appears, you can select the language, and keyboard layout and continue. Enter your login and name. Remember the credentials as you will need them to log in to your system and access full privileges. Wait for the installation to complete.</p>
</li>
<li><p><strong>Step 5 – Restart:</strong> Click on restart now and remove the pen drive.</p>
</li>
<li><p><strong>Step 6 – Login:</strong> Login with the credentials you entered earlier.</p>
</li>
</ul>
<p>And there you go! Now you can install apps and customize your desktop.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304547967/d150c6eb-d04e-47e0-8473-d1a837df45c4.png" alt="Ubuntu 22.04.4 LTS Desktop screen" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>For advanced installation, you can explore the following topics:</p>
<ul>
<li><p>Disk partitioning.</p>
</li>
<li><p>Setting swap memory for enabling hibernation.</p>
</li>
</ul>
<p><strong>Accessing the terminal</strong></p>
<p>An important part of this handbook is learning about the terminal where you'll run all the commands and see the magic happen. You can search for the terminal by pressing the "windows" key and typing "terminal". You can pin the Terminal in the dock where other apps are located for easy access.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305113272/4dd30c5e-da73-4cd4-86bb-7dcd8cd2084c.png" alt="Search results for &quot;terminal&quot;" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>💡 The shortcut for opening the terminal is <code>ctrl+alt+t</code></p>
</blockquote>
<p>You can also open the terminal from inside a folder. Right click where you are and click on "Open in Terminal". This will open the terminal in the same path.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305289021/284a4a53-2d1a-4eaa-925a-1002a32c1dce.png" alt="Opening the terminal with right click menu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-use-linux-on-a-windows-machine">How to use Linux on a Windows machine</h5>
<p>Sometimes you might need to run both Linux and Windows side by side. Luckily, there are some ways you can get the best of both worlds without getting different computers for each operating system.</p>
<p>In this section, you'll explore a few ways to use Linux on a Windows machine. Some of them are browser-based or cloud-based and do not need any OS installation before using them.</p>
<p><strong>Option 1: "Dual-boot" Linux + Windows</strong> With dual boot, you can install Linux alongside Windows on your computer, allowing you to choose which operating system to use at startup.</p>
<p>This requires partitioning your hard drive and installing Linux on a separate partition. With this approach, you can only use one operating system at a time.</p>
<p><strong>Option 2: Use Windows Subsystem for Linux (WSL)</strong> Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.</p>
<p>Using WSL has some advantages. The setup for WSL is simple and not time-consuming. It is lightweight compared to VMs where you have to allocate resources from the host machine. You don't need to install any ISO or virtual disc image for Linux machines which tend to be heavy files. You can use Windows and Linux side by side.</p>
<p><strong>How to install WSL2</strong></p>
<p>First, enable the Windows Subsystem for Linux option in settings.</p>
<ul>
<li><p>Go to Start. Search for "Turn Windows features on or off."</p>
</li>
<li><p>Check the option "Windows Subsystem for Linux" if it isn't already.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306102095/84f23bae-faa5-4ece-a9b6-e40f8789a061.png" alt="Checking the option &quot;Windows Subsystem for Linux&quot; in Windows features" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Next, open your command prompt and provide the installation commands.</p>
</li>
<li><p>Open Command Prompt as an administrator:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720451480640/6052c9b4-cf07-47e0-ae89-18c3a2d3e385.png" alt="Running command prompt as an admin by right clicking the app and choosing &quot;run as admin£" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Run the command below:</p>
</li>
</ul>
<pre><code class="lang-markdown">wsl --install
</code></pre>
<p>This is the output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306131053/b7272031-ddb7-4e04-8d7b-bafc0911da04.png" alt="Downloading progress of Ubuntu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Note: By default, Ubuntu will be installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306144861/a01f95df-1d95-4b79-bff9-08759be0d3dc.png" alt="Ubuntu installed by default using WSL" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<ul>
<li>Once installation is complete, you'll need to reboot your Windows machine. So, restart your Windows machine.</li>
</ul>
<p>After restarting, you might see a window like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306157704/15620fbe-59d1-40da-9cd6-119a1fab0802.png" alt="Window that shows after a restart" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Once installation of Ubuntu is complete, you'll be prompted to enter your username and password.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306167380/5e3058cd-b7a1-45b1-a16d-c23b5a451504.png" alt="User prompted to enter a username and password" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>And, that's it! You are ready to use Ubuntu.</p>
<p>Launch Ubuntu by searching from the start menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306185110/77c17856-08ac-4ec7-9380-5b06f93be095.png" alt="Launching Ubuntu from the start menu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>And here we have your Ubuntu instance launched.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306196320/13be3a71-5b40-440c-a6bf-d742e5b5934b.png" alt="Successful installation of Ubuntu using WSL" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Option 3: Use a Virtual Machine (VM)</strong></p>
<p>A virtual machine (VM) is a software emulation of a physical computer system. It allows you to run multiple operating systems and applications on a single physical machine simultaneously.</p>
<p>You can use virtualization software such as Oracle VirtualBox or VMware to create a virtual machine running Linux within your Windows environment. This allows you to run Linux as a guest operating system alongside Windows.</p>
<p>VM software provides options to allocate and manage hardware resources for each VM, including CPU cores, memory, disk space, and network bandwidth. You can adjust these allocations based on the requirements of the guest operating systems and applications.</p>
<p>Here are some of the common options available for virtualization:</p>
<ul>
<li><p><a target="_blank" href="https://www.virtualbox.org/">Oracle virtual box</a></p>
</li>
<li><p><a target="_blank" href="https://multipass.run/">Multipass</a></p>
</li>
<li><p><a target="_blank" href="https://www.vmware.com/content/vmware/vmware-published-sites/us/products/workstation-player.html.html">VMware workstation player</a></p>
</li>
</ul>
<p><strong>Option 4: Use a Browser-based Solution</strong></p>
<p>Browser-based solutions are particularly useful for quick testing, learning, or accessing Linux environments from devices that don't have Linux installed.</p>
<p>You can either use online code editors or web-based terminals to access Linux. Note that you usually don't have full administration privileges in these cases.</p>
<h4 id="heading-online-code-editors"><strong>Online code editors</strong></h4>
<p>Online code editors offer editors with built-in Linux terminals. While their primary purpose is coding, you can also utilize the Linux terminal to execute commands and perform tasks.</p>
<p><a target="_blank" href="https://replit.com/">Replit</a> is an example of an online code editor, where you can write your code and access the Linux shell at the same time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306257260/d85d5541-b78f-4c8b-99a8-dbd8c097f661.gif" alt="Running scripts and a bash shell in Replit" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-web-based-linux-terminals"><strong>Web-based Linux terminals:</strong></h4>
<p>Online Linux terminals allow you to access a Linux command-line interface directly from your browser. These terminals provide a web-based interface to a Linux shell, enabling you to execute commands and work with Linux utilities.</p>
<p>One such example is <a target="_blank" href="https://jslinux.org/">JSLinux</a>. The screenshot below shows a ready-to-use Linux environment:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306276915/ddaabfc3-9a20-43b2-bedc-0af6875d2008.png" alt="Using JSLinux to access Linux terminal" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Option 5: Use a Cloud-based Solution</strong></p>
<p>Instead of running Linux directly on your Windows machine, you can consider using cloud-based Linux environments or virtual private servers (VPS) to access and work with Linux remotely.</p>
<p>Services like Amazon EC2, Microsoft Azure, or DigitalOcean provide Linux instances that you can connect to from your Windows computer. Note that some of these services offer free tiers, but they are not usually free in the long run.</p>
<h2 id="heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</h2>
<h3 id="heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</h3>
<h4 id="heading-introduction-to-the-bash-shell">Introduction to the bash shell</h4>
<p>The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.</p>
<p>Different users can be configured to use different shells. But, most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (<code>bash</code>). Bash is succeeded by the Bourne shell (<code>sh</code>).</p>
<p>To find out your current shell, open your terminal and enter the following command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
</code></pre>
<p>Command breakdown:</p>
<ul>
<li><p>The <code>echo</code> command is used to print on the terminal.</p>
</li>
<li><p>The <code>$SHELL</code> is a special variable that holds the name of the current shell.</p>
</li>
</ul>
<p>In my setup, the output is <code>/bin/bash</code>. This means that I am using the bash shell.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># output</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
/bin/bash
</code></pre>
<p>Bash is very powerful as it can simplify certain operations that are hard to accomplish efficiently with a GUI (or Graphical User Interface). Remember that most servers do not have a GUI, and it is best to learn to use the powers of a command line interface (CLI).</p>
<p><strong>Terminal vs Shell</strong></p>
<p>The terms "terminal" and "shell" are often used interchangeably, but they refer to different parts of the command-line interface.</p>
<p>The terminal is the interface you use to interact with the shell. The shell is the command interpreter that processes and executes your commands. You'll learn more about shells in Part 6 of the handbook.</p>
<h4 id="heading-what-is-a-prompt">What is a prompt?</h4>
<p>When a shell is used interactively, it displays a <code>$</code> when it is waiting for a command from the user. This is called the shell prompt.</p>
<p><code>[username@host ~]$</code></p>
<p>If the shell is running as <code>root</code> (you'll learn more about the root user later on), the prompt is changed to <code>#</code>.</p>
<p><code>[root@host ~]#</code></p>
<h3 id="heading-22-command-structure">2.2. Command Structure</h3>
<p>A command is a program that performs a specific operation. Once you have access to the shell, you can enter any command after the <code>$</code> sign and see the output on the terminal.</p>
<p>Generally, Linux commands follow this syntax:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">command</span> [options] [arguments]
</code></pre>
<p>Here is the breakdown of the above syntax:</p>
<ul>
<li><p><code>command</code>: This is the name of the command you want to execute. <code>ls</code> (list), <code>cp</code> (copy), and <code>rm</code> (remove) are common Linux commands.</p>
</li>
<li><p><code>[options]</code>: Options, or flags, often preceded by a hyphen (-) or double hyphen (--), modify the behavior of the command. They can change how the command operates. For example, <code>ls -a</code> uses the <code>-a</code> option to display hidden files in the current directory.</p>
</li>
<li><p><code>[arguments]</code>: Arguments are the inputs for the commands that require one. These could be filenames, user names, or other data that the command will act upon. For example, in the command <code>cat access.log</code>, <code>cat</code> is the command and <code>access.log</code> is the input. As a result, the <code>cat</code> command displays the contents of the <code>access.log</code> file.</p>
</li>
</ul>
<p>Options and arguments are not required for all commands. Some commands can be run without any options or arguments, while others might require one or both to function correctly. You can always refer to the command's manual to check the options and arguments it supports.</p>
<p>💡<strong>Tip:</strong> You can view a command's manual using the <code>man</code> command.</p>
<p>You can access the manual page for <code>ls</code> with <code>man ls</code>, and it'll look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719312523336/5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7.png" alt="5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Manual pages are a great and quick way to access the documentation. I highly recommend going through man pages for the commands that you use the most.</p>
<h3 id="heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</h3>
<p>When you are in the terminal, you can speed up your tasks by using shortcuts.</p>
<p>Here are some of the most common terminal shortcuts:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Shortcut</td></tr>
</thead>
<tbody>
<tr>
<td>Look for the previous command</td><td>Up Arrow</td></tr>
<tr>
<td>Jump to the beginning of the previous word</td><td>Ctrl+LeftArrow</td></tr>
<tr>
<td>Clear characters from the cursor to the end of the command line</td><td>Ctrl+K</td></tr>
<tr>
<td>Complete commands, file names, and options</td><td>Pressing Tab</td></tr>
<tr>
<td>Jumps to the beginning of the command line</td><td>Ctrl+A</td></tr>
<tr>
<td>Displays the list of previous commands</td><td>history</td></tr>
</tbody>
</table>
</div><h3 id="heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</h3>
<p>You can get the username you are logged in with by using the <code>whoami</code> command. This command is useful when you are switching between different users and want to confirm the current user.</p>
<p>Just after the <code>$</code> sign, type <code>whoami</code> and press enter.</p>
<pre><code class="lang-bash">whoami
</code></pre>
<p>This is the output I got.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ whoami
zaira
</code></pre>
<h2 id="heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</h2>
<h3 id="heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</h3>
<h4 id="heading-print-system-information-using-the-uname-command">Print system information using the <code>uname</code> Command</h4>
<p>You can get detailed system information from the <code>uname</code> command.</p>
<p>When you provide the <code>-a</code> option, it prints all the system information.</p>
<pre><code class="lang-bash">uname -a
<span class="hljs-comment"># output</span>
Linux zaira 6.5.0-21-generic <span class="hljs-comment">#21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb  9 13:32:52 UTC 2 x86_64 x86_64 x86_64 GNU/Linux</span>
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>Linux</code>: Indicates the operating system.</p>
</li>
<li><p><code>zaira</code>: Represents the hostname of the machine.</p>
</li>
<li><p><code>6.5.0-21-generic #21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 9 13:32:52 UTC 2</code>: Provides information about the kernel version, build date, and some additional details.</p>
</li>
<li><p><code>x86_64 x86_64 x86_64</code>: Indicates the architecture of the system.</p>
</li>
<li><p><code>GNU/Linux</code>: Represents the operating system type.</p>
</li>
</ul>
<h4 id="heading-find-details-of-the-cpu-architecture-using-the-lscpu-command">Find details of the CPU architecture using the <code>lscpu</code> Command</h4>
<p>The <code>lscpu</code> command in Linux is used to display information about the CPU architecture. When you run <code>lscpu</code> in the terminal, it provides details such as:</p>
<ul>
<li><p>The architecture of the CPU (for example, x86_64)</p>
</li>
<li><p>CPU op-mode(s) (for example, 32-bit, 64-bit)</p>
</li>
<li><p>Byte Order (for example, Little Endian)</p>
</li>
<li><p>CPU(s) (number of CPUs), and so on</p>
<p>  Let's try it out:</p>
</li>
</ul>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
Vendor ID:               AuthenticAMD
  Model name:            AMD Ryzen 5 5500U with Radeon Graphics
    Thread(s) per core:  2
    Core(s) per socket:  6
    Socket(s):           1
    Stepping:            1
    CPU max MHz:         4056.0000
    CPU min MHz:         400.0000
</code></pre>
<p>That was a whole lot of information, but useful too! Remember you can always skim the relevant information using specific flags. See the command manual with <code>man lscpu</code>.</p>
<h2 id="heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</h2>
<h3 id="heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</h3>
<p>All files in Linux are stored in a file-system. It follows an inverted-tree-like structure because the root is at the topmost part.</p>
<p>The <code>/</code> is the root directory and the starting point of the file system. The root directory contains all other directories and files on the system. The <code>/</code> character also serves as a directory separator between path names. For example, <code>/home/alice</code> forms a complete path.</p>
<p>The image below shows the complete file system hierarchy. Each directory servers a specific purpose.</p>
<p>Note that this is not an exhaustive list and different distributions may have different configurations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322457140/02fdbf2c-f4fa-438b-af2f-c23f59f9ddf4.png" alt="Linux file system hierarchy" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Here is a table that shows the purpose of each directory:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Location</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td>/bin</td><td>Essential command binaries</td></tr>
<tr>
<td>/boot</td><td>Static files of the boot loader, needed in order to start the boot process.</td></tr>
<tr>
<td>/etc</td><td>Host-specific system configuration</td></tr>
<tr>
<td>/home</td><td>User home directories</td></tr>
<tr>
<td>/root</td><td>Home directory for the administrative root user</td></tr>
<tr>
<td>/lib</td><td>Essential shared libraries and kernel modules</td></tr>
<tr>
<td>/mnt</td><td>Mount point for mounting a filesystem temporarily</td></tr>
<tr>
<td>/opt</td><td>Add-on application software packages</td></tr>
<tr>
<td>/usr</td><td>Installed software and shared libraries</td></tr>
<tr>
<td>/var</td><td>Variable data that is also persistent between boots</td></tr>
<tr>
<td>/tmp</td><td>Temporary files that are accessible to all users</td></tr>
</tbody>
</table>
</div><p>💡 <strong>Tip:</strong> You can learn more about the file system using the <code>man hier</code> command.</p>
<p>You can check your file system using the <code>tree -d -L 1</code> command. You can modify the <code>-L</code> flag to change the depth of the tree.</p>
<pre><code class="lang-bash">tree -d -L 1
<span class="hljs-comment"># output</span>
.
├── bin -&gt; usr/bin
├── boot
├── cdrom
├── data
├── dev
├── etc
├── home
├── lib -&gt; usr/lib
├── lib32 -&gt; usr/lib32
├── lib64 -&gt; usr/lib64
├── libx32 -&gt; usr/libx32
├── lost+found
├── media
├── mnt
├── opt
├── proc
├── root
├── run
├── sbin -&gt; usr/sbin
├── snap
├── srv
├── sys
├── tmp
├── usr
└── var

25 directories
</code></pre>
<p>This list is not exhaustive and different distributions and systems may be configured differently.</p>
<h3 id="heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</h3>
<h4 id="heading-absolute-path-vs-relative-path">Absolute path vs relative path</h4>
<p>The absolute path is the full path from the root directory to the file or directory. It always starts with a <code>/</code>. For example, <code>/home/john/documents</code>.</p>
<p>The relative path, on the other hand, is the path from the current directory to the destination file or directory. It does not start with a <code>/</code>. For example, <code>documents/work/project</code>.</p>
<h4 id="heading-locating-your-current-directory-using-the-pwd-command">Locating your current directory using the <code>pwd</code> command</h4>
<p>It is easy to lose your way in the Linux file system, especially if you are new to the command line. You can locate your current directory using the <code>pwd</code> command.</p>
<p>Here is an example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
<span class="hljs-comment"># output</span>
/home/zaira/scripts/python/free-mem.py
</code></pre>
<h4 id="heading-changing-directories-using-the-cd-command">Changing directories using the <code>cd</code> command</h4>
<p>The command to change directories is <code>cd</code> and it stands for "change directory". You can use the <code>cd</code> command to navigate to a different directory.</p>
<p>You can use a relative path or an absolute path.</p>
<p>For example, if you want to navigate the below file structure (following the red lines):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719389950079/640cce46-6c52-4f38-9787-581747fb9798.png" alt="Example file structure" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>and you are standing at "home", the command would be like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> home/bob/documents/work/project
</code></pre>
<p>Some other commonly used <code>cd</code> shortcuts are:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>cd ..</code></td><td>Go back one directory</td></tr>
<tr>
<td><code>cd ../..</code></td><td>Go back two directories</td></tr>
<tr>
<td><code>cd</code> or <code>cd ~</code></td><td>Go to the home directory</td></tr>
<tr>
<td><code>cd -</code></td><td>Go to the previous path</td></tr>
</tbody>
</table>
</div><h3 id="heading-43-managing-files-and-directories">4.3. Managing Files and Directories</h3>
<p>When working with files and directories, you might want to copy, move, remove, and create new files and directories. Here are some commands that can help you with that.</p>
<p>💡<strong>Tip:</strong> You can differentiate between a file and folder by looking at the first letter in the output of <code>ls -l</code>. A<code>'-'</code> represents a file and a <code>'d'</code> represents a folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719390306244/4f1688cd-ded5-43fe-b13a-9ca44ac7c4ad.png" alt="&quot;d&quot; represents a folder" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-creating-new-directories-using-the-mkdir-command">Creating new directories using the <code>mkdir</code> command</h4>
<p>You can create an empty directory using the <code>mkdir</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates an empty directory named "foo" in the current folder</span>
mkdir foo
</code></pre>
<p>You can also create directories recursively using the <code>-p</code> option.</p>
<pre><code class="lang-bash">mkdir -p tools/index/helper-scripts
<span class="hljs-comment"># output of tree</span>
.
└── tools
    └── index
        └── helper-scripts

3 directories, 0 files
</code></pre>
<h4 id="heading-creating-new-files-using-the-touch-command">Creating new files using the <code>touch</code> command</h4>
<p>The <code>touch</code> command creates an empty file. You can use it like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty file "file.txt" in the current folder</span>
touch file.txt
</code></pre>
<p>The file names can be chained together if you want to create multiple files in a single command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty files "file1.txt", "file2.txt", and "file3.txt" in the current folder</span>

touch file1.txt file2.txt file3.txt
</code></pre>
<h4 id="heading-removing-files-and-directories-using-the-rm-and-rmdir-command">Removing files and directories using the <code>rm</code> and <code>rmdir</code> command</h4>
<p>You can use the <code>rm</code> command to remove both files and non-empty directories.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>rm file.txt</code></td><td>Removes the file <code>file.txt</code></td></tr>
<tr>
<td><code>rm -r directory</code></td><td>Removes the directory <code>directory</code> and its contents</td></tr>
<tr>
<td><code>rm -f file.txt</code></td><td>Removes the file <code>file.txt</code> without prompting for confirmation</td></tr>
<tr>
<td><code>rmdir</code> directory</td><td>Removes an empty directory</td></tr>
</tbody>
</table>
</div><p>🛑 Note that you should use the <code>-f</code> flag with caution as you won't be asked before deleting a file. Also, be careful when running <code>rm</code> commands in the <code>root</code> folder as it might result in deleting important system files.</p>
<h4 id="heading-copying-files-using-the-cp-command">Copying files using the <code>cp</code> command</h4>
<p>To copy files in Linux, use the <code>cp</code> command.</p>
<ul>
<li><strong>Syntax to copy files:</strong><code>cp source_file destination_of_file</code></li>
</ul>
<p>This command copies a file named <code>file1.txt</code> to a new file location <code>/home/adam/logs</code>.</p>
<pre><code class="lang-bash">cp file1.txt /home/adam/logs
</code></pre>
<p>The <code>cp</code> command also creates a copy of one file with the provided name.</p>
<p>This command copies a file named <code>file1.txt</code> to another file named <code>file2.txt</code> in the same folder.</p>
<pre><code class="lang-bash">cp file1.txt file2.txt
</code></pre>
<h4 id="heading-moving-and-renaming-files-and-folders-using-the-mv-command">Moving and renaming files and folders using the <code>mv</code> command</h4>
<p>The <code>mv</code> command is used to move files and folders from one directory to the other.</p>
<p><strong>Syntax to move files:</strong><code>mv source_file destination_directory</code></p>
<p><strong>Example:</strong> Move a file named <code>file1.txt</code> to a directory named <code>backup</code>:</p>
<pre><code class="lang-bash">mv file1.txt backup/
</code></pre>
<p>To move a directory and its contents:</p>
<pre><code class="lang-bash">mv dir1/ backup/
</code></pre>
<p>Renaming files and folders in Linux is also done with the <code>mv</code> command.</p>
<p><strong>Syntax to rename files:</strong><code>mv old_name new_name</code></p>
<p><strong>Example:</strong> Rename a file from <code>file1.txt</code> to <code>file2.txt</code>:</p>
<pre><code class="lang-bash">mv file1.txt file2.txt
</code></pre>
<p>Rename a directory from <code>dir1</code> to <code>dir2</code>:</p>
<pre><code class="lang-bash">mv dir1 dir2
</code></pre>
<h3 id="heading-44-locating-files-and-folders-using-the-find-command">4.4. Locating Files and Folders Using the <code>find</code> Command</h3>
<p>The <code>find</code> command lets you efficiently search for files, folders, and character and block devices.</p>
<p>Below is the basic syntax of the <code>find</code> command:</p>
<pre><code class="lang-bash">find /path/ -<span class="hljs-built_in">type</span> f -name file-to-search
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>/path</code> is the path where the file is expected to be found. This is the starting point for searching files. The path can also be<code>/</code>or <code>.</code> which represents the root and current directory, respectively.</p>
</li>
<li><p><code>-type</code> represents the file descriptors. They can be any of the below:<br>  <code>f</code> – <strong>Regular file</strong> such as text files, images, and hidden files.<br>  <code>d</code> – <strong>Directory</strong>. These are the folders under consideration.<br>  <code>l</code> – <strong>Symbolic link</strong>. Symbolic links point to files and are similar to shortcuts.<br>  <code>c</code> – <strong>Character devices</strong>. Files that are used to access character devices are called character device files. Drivers communicate with character devices by sending and receiving single characters (bytes, octets). Examples include keyboards, sound cards, and the mouse.<br>  <code>b</code> – <strong>Block devices</strong>. Files that are used to access block devices are called block device files. Drivers communicate with block devices by sending and receiving entire blocks of data. Examples include USB and CD-ROM</p>
</li>
<li><p><code>-name</code> is the name of the file type that you want to search.</p>
</li>
</ul>
<h4 id="heading-how-to-search-files-by-name-or-extension">How to search files by name or extension</h4>
<p>Suppose we need to find files that contain "style" in their name. We'll use this command:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"style*"</span>
<span class="hljs-comment">#output</span>
./style.css
./styles.css
</code></pre>
<p>Now let's say we want to find files with a particular extension like <code>.html</code>. We'll modify the command like this:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.html"</span>
<span class="hljs-comment"># output</span>
./services.html
./blob.html
./index.html
</code></pre>
<h4 id="heading-how-to-search-hidden-files">How to search hidden files</h4>
<p>A dot at the beginning of the filename represents hidden files. They are normally hidden but can be viewed with <code>ls -a</code> in the current directory.</p>
<p>We can modify the <code>find</code> command as shown below to search for hidden files:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
</code></pre>
<p><strong>List and find hidden files</strong></p>
<pre><code class="lang-bash">ls -la
<span class="hljs-comment"># folder contents</span>
total 5
drwxrwxr-x  2 zaira zaira 4096 Mar 26 14:17 .
drwxr-x--- 61 zaira zaira 4096 Mar 26 14:12 ..
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_history
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_logout
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bashrc

find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
<span class="hljs-comment"># find output</span>
./.bash_logout
./.bashrc
./.bash_history
</code></pre>
<p>Above you can see a list of hidden files in my home directory.</p>
<h4 id="heading-how-to-search-log-files-and-configuration-files">How to search log files and configuration files</h4>
<p>Log files usually have the extension <code>.log</code>, and we can find them like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.log"</span>
</code></pre>
<p>Similarly, we can search for configuration files like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.conf"</span>
</code></pre>
<h4 id="heading-how-to-search-other-files-by-type">How to search other files by type</h4>
<p>We can search for character block files by providing <code>c</code> to <code>-type</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> c
</code></pre>
<p>Similarly, we can find device block files by using <code>b</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> b
</code></pre>
<h4 id="heading-how-to-search-directories">How to search directories</h4>
<p>In the example below, we are finding the folders using the <code>-type d</code> flag.</p>
<pre><code class="lang-bash">ls -l
<span class="hljs-comment"># list folder contents</span>
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 hosts
-rw-rw-r-- 1 zaira zaira    0 Mar 26 14:23 hosts.txt
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 images
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:23 style
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 webp 

find . -<span class="hljs-built_in">type</span> d 
<span class="hljs-comment"># find directory output</span>
.
./webp
./images
./style
./hosts
</code></pre>
<h4 id="heading-how-to-search-files-by-size">How to search files by size</h4>
<p>An incredibly helpful use of the <code>find</code> command is to list files based on a particular size.</p>
<pre><code class="lang-bash">find / -size +250M
</code></pre>
<p>Here, we are listing files whose size exceeds <code>250MB</code>.</p>
<p>Other units include:</p>
<ul>
<li><p><code>G</code>: GigaBytes.</p>
</li>
<li><p><code>M</code>: MegaBytes.</p>
</li>
<li><p><code>K</code>: KiloBytes</p>
</li>
<li><p><code>c</code> : bytes.</p>
</li>
</ul>
<p>Just replace with the relevant unit.</p>
<pre><code class="lang-bash">find &lt;directory&gt; -<span class="hljs-built_in">type</span> f -size +N&lt;Unit Type&gt;
</code></pre>
<h4 id="heading-how-to-search-files-by-modification-time">How to search files by modification time</h4>
<p>By using the <code>-mtime</code> flag, you can filter files and folders based on the modification time.</p>
<pre><code class="lang-bash">find /path -name <span class="hljs-string">"*.txt"</span> -mtime -10
</code></pre>
<p>For example,</p>
<ul>
<li><p><strong>-mtime +10</strong> means you are looking for a file modified 10 days ago.</p>
</li>
<li><p><strong>-mtime -10</strong> means less than 10 days.</p>
</li>
<li><p><strong>-mtime 10</strong> If you skip + or – it means exactly 10 days.</p>
</li>
</ul>
<h3 id="heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</h3>
<h4 id="heading-concatenate-and-display-files-using-the-cat-command">Concatenate and display files using the <code>cat</code> command</h4>
<p>The <code>cat</code> command in Linux is used to display the contents of a file. It can also be used to concatenate files and create new files.</p>
<p>Here is the basic syntax of the <code>cat</code> command:</p>
<pre><code class="lang-bash">cat [options] [file]
</code></pre>
<p>The simplest way to use <code>cat</code> is without any options or arguments. This will display the contents of the file on the terminal.</p>
<p>For example, if you want to view the contents of a file named <code>file.txt</code>, you can use the following command:</p>
<pre><code class="lang-bash">cat file.txt
</code></pre>
<p>This will display all the contents of the file on the terminal at once.</p>
<h4 id="heading-viewing-text-files-interactively-using-less-and-more">Viewing text files interactively using <code>less</code> and <code>more</code></h4>
<p>While <code>cat</code> displays the entire file at once, <code>less</code> and <code>more</code> allow you to view the contents of a file interactively. This is useful when you want to scroll through a large file or search for specific content.</p>
<p>The syntax of the <code>less</code> command is:</p>
<pre><code class="lang-bash">less [options] [file]
</code></pre>
<p>The <code>more</code> command is similar to <code>less</code> but has fewer features. It is used to display the contents of a file one screen at a time.</p>
<p>The syntax of the <code>more</code> command is:</p>
<pre><code class="lang-bash">more [options] [file]
</code></pre>
<p>For both commands, you can use the <code>spacebar</code> to scroll one page down, the <code>Enter</code> key to scroll one line down, and the <code>q</code> key to exit the viewer.</p>
<p>To move backward you can use the <code>b</code> key, and to move forward you can use the <code>f</code> key.</p>
<h4 id="heading-displaying-the-last-part-of-files-using-tail">Displaying the last part of files using <code>tail</code></h4>
<p>Sometimes you might need to view just the last few lines of a file instead of the entire file. The <code>tail</code> command in Linux is used to display the last part of a file.</p>
<p>For example, <code>tail file.txt</code> will display the last 10 lines of the file <code>file.txt</code> by default.</p>
<p>If you want to display a different number of lines, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Display the last 50 lines of the file file.txt</span>
tail -n 50 file.txt
</code></pre>
<p>💡<strong>Tip:</strong> Another usage of the <code>tail</code> is its follow-along (<code>-f</code>) option. This option enables you to view the contents of a file as they are being written. This is a useful utility for viewing and monitoring log files in real-time.</p>
<h4 id="heading-displaying-the-beginning-of-files-using-head">Displaying the beginning of files using <code>head</code></h4>
<p>Just like <code>tail</code> displays the last part of a file, you can use the <code>head</code> command in Linux to display the beginning of a file.</p>
<p>For example, <code>head file.txt</code> will display the first 10 lines of the file <code>file.txt</code> by default.</p>
<p>To change the number of lines displayed, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<h4 id="heading-counting-words-lines-and-characters-using-wc">Counting words, lines, and characters using <code>wc</code></h4>
<p>You can count words, lines and characters in a file using the <code>wc</code> command.</p>
<p>For example, running <code>wc syslog.log</code> gave me the following output:</p>
<pre><code class="lang-bash">1669 9623 64367 syslog.log
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>1669</code> represents the number of lines in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>9623</code> represents the number of words in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>64367</code> represents the number of characters in the file <code>syslog.log</code>.</p>
</li>
</ul>
<p>So, the command <code>wc syslog.log</code> counted <code>1669</code> lines, <code>9623</code> words, and <code>64367</code> characters in the file <code>syslog.log</code>.</p>
<h4 id="heading-comparing-files-line-by-line-using-diff">Comparing files line by line using <code>diff</code></h4>
<p>Comparing and finding differences between two files is a common task in Linux. You can compare two files right within the command line using the <code>diff</code> command.</p>
<p>The basic syntax of the <code>diff</code> command is:</p>
<pre><code class="lang-bash">diff [options] file1 file2
</code></pre>
<p>Here are two files, <code>hello.py</code> and <code>also-hello.py</code>, that we will compare using the <code>diff</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of hello.py</span>

def greet(name):
    <span class="hljs-built_in">return</span> f<span class="hljs-string">"Hello, {name}!"</span>

user = input(<span class="hljs-string">"Enter your name: "</span>)
<span class="hljs-built_in">print</span>(greet(user))
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of also-hello.py</span>

more also-hello.py
def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<ol>
<li>Check whether the files are the same or not</li>
</ol>
<pre><code class="lang-bash">diff -q hello.py also-hello.py
<span class="hljs-comment"># Output</span>
Files hello.py and also-hello.py differ
</code></pre>
<ol start="2">
<li>See how the files differ. For that, you can use the <code>-u</code> flag to see a unified output:</li>
</ol>
<pre><code class="lang-bash">diff -u hello.py also-hello.py
--- hello.py    2024-05-24 18:31:29.891690478 +0500
+++ also-hello.py    2024-05-24 18:32:17.207921795 +0500
@@ -3,4 +3,5 @@

 user = input(Enter your name: )
 <span class="hljs-built_in">print</span>(greet(user))
+<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the above output:</p>
<ul>
<li><p><code>--- hello.py 2024-05-24 18:31:29.891690478 +0500</code> indicates the file being compared and its timestamp.</p>
</li>
<li><p><code>+++ also-hello.py 2024-05-24 18:32:17.207921795 +0500</code> indicates the other file being compared and its timestamp.</p>
</li>
<li><p><code>@@ -3,4 +3,5 @@</code> shows the line numbers where the changes occur. In this case, it indicates that lines 3 to 4 in the original file have changed to lines 3 to 5 in the modified file.</p>
</li>
<li><p><code>user = input(Enter your name: )</code> is a line from the original file.</p>
</li>
<li><p><code>print(greet(user))</code> is another line from the original file.</p>
</li>
<li><p><code>+print("Nice to meet you")</code> is the additional line in the modified file.</p>
</li>
</ul>
<ol start="3">
<li>To see the diff in a side-by-side format, you can use the <code>-y</code> flag:</li>
</ol>
<pre><code class="lang-bash">diff -y hello.py also-hello.py
<span class="hljs-comment"># Output</span>
def greet(name):                        def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!                        <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )                    user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))                        <span class="hljs-built_in">print</span>(greet(user))
                                        &gt;    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the output:</p>
<ul>
<li><p>The lines that are the same in both files are displayed side by side.</p>
</li>
<li><p>Lines that are different are shown with a <code>&gt;</code> symbol indicating the line is only present in one of the files.</p>
</li>
</ul>
<h2 id="heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</h2>
<p>Text editing skills using the command line are one of the most crucial skills in Linux. In this section, you will learn how to use two popular text editors in Linux: Vim and Nano.</p>
<p>I suggest that you master any one text editor of your choice and stick to it. It will save you time and make you more productive. Vim and nano are safe choices as they are present on most Linux distributions.</p>
<h3 id="heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</h3>
<h4 id="heading-introduction-to-vim">Introduction to Vim</h4>
<p>Vim is a popular text editing tool for the command line. Vim comes with its advantages: it is powerful, customizable, and fast. Here are some reasons why you should consider learning Vim:</p>
<ul>
<li><p>Most servers are accessed via a CLI, so in system administration, you don't necessarily have the luxury of a GUI. But Vim has got your back – it'll always be there.</p>
</li>
<li><p>Vim uses a keyboard-centric approach, as it is designed to be used without a mouse, which can significantly speed up editing tasks once you have learned the keyboard shortcuts. This also makes it faster than GUI tools.</p>
</li>
<li><p>Some Linux utilities, for example editing cron jobs, work in the same editing format as Vim.</p>
</li>
<li><p>Vim is suitable for all – beginners and advanced users. Vim supports complex string searches, highlighting searches, and much more. Through plugins, Vim provides extended capabilities to developers and system admins that includes code completion, syntax highlighting, file management, version control, and more.</p>
</li>
</ul>
<p>Vim has two variations: Vim (<code>vim</code>) and Vim tiny (<code>vi</code>). Vim tiny is a smaller version of Vim that lacks some features of Vim.</p>
<h4 id="heading-how-to-start-using-vim">How to start using <code>vim</code></h4>
<p>Start using Vim with this command:</p>
<pre><code class="lang-bash">vim your-file.txt
</code></pre>
<p><code>your-file.txt</code> can either be a new file or an existing file that you want to edit.</p>
<h4 id="heading-navigating-vim-mastering-movement-and-command-modes">Navigating Vim: Mastering movement and command modes</h4>
<p>In the early days of the CLI, the keyboards didn't have arrow keys. Hence, navigation was done using the set of available keys, <code>hjkl</code> being one of them.</p>
<p>Being keyboard-centric, using <code>hjkl</code> keys can greatly speed up text editing tasks.</p>
<p>Note: Although arrow keys would work totally fine, you can still experiment with <code>hjkl</code> keys to navigate. Some people find this this way of navigation efficient.</p>
<p>💡<strong>Tip:</strong> To remember the <code>hjkl</code> sequence, use this: <strong>h</strong>ang back, <strong>j</strong>ump down, <strong>k</strong>ick up, <strong>l</strong>eap forward.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392462442/1a667ede-5f03-4acb-b40f-b10cefc64de3.png" alt="hjkl navigation guide" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-the-three-vim-modes">The three Vim modes</h4>
<p>You need to know the 3 operating modes of Vim and how to switch between them. Keystrokes behave differently in each command mode. The three modes are as follows:</p>
<ol>
<li><p>Command mode.</p>
</li>
<li><p>Edit mode.</p>
</li>
<li><p>Visual mode.</p>
</li>
</ol>
<p><strong>Command Mode.</strong> When you start Vim, you land in the command mode by default. This mode allows you to access other modes.</p>
<p>⚠ To switch to other modes, you need to be present in the command mode first</p>
<p><strong>Edit Mode</strong></p>
<p>This mode allows you to make changes to the file. To enter edit mode, press <code>I</code> while in command mode. Note the <code>'-- INSERT'</code> switch at the end of the screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392526710/d44cecd7-64be-4c89-9a31-dbf395b77fcb.png" alt="Insert mode in Vim" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Visual mode</strong></p>
<p>This mode allows you to work on a single character, a block of text, or lines of text. Let's break it down into simple steps. Remember, use the below combinations when in command mode.</p>
<ul>
<li><p><code>Shift + V</code> → Select multiple lines.</p>
</li>
<li><p><code>Ctrl + V</code> → Block mode</p>
</li>
<li><p><code>V</code> → Character mode</p>
</li>
</ul>
<p>The visual mode comes in handy when you need to copy and paste or edit lines in bulk.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392557097/b61a1515-cac0-4470-856b-b2c15de581e8.gif" alt="Selectind text using visual mode" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Extended command mode.</strong></p>
<p>The extended command mode allows you to perform advanced operations like searching, setting line numbers, and highlighting text. We'll cover extended mode in the next section.</p>
<p>How to stay on track? If you forget your current mode, just press <code>ESC</code> twice and you will be back in Command Mode.</p>
<h4 id="heading-editing-efficiently-in-vim-copypasting-and-searching">Editing Efficiently in Vim: Copy/pasting and searching</h4>
<p><strong>1. How to copy and paste in Vim</strong></p>
<p>Copy-paste is known as 'yank' and 'put' in Linux terms. To copy-paste, follow these steps:</p>
<ul>
<li><p>Select text in visual mode.</p>
</li>
<li><p>Press <code>'y'</code> to copy/ yank.</p>
</li>
<li><p>Move your cursor to the required position and press <code>'p'</code>.</p>
</li>
</ul>
<p><strong>2. How to search for text in Vim</strong></p>
<p>Any series of strings can be searched with Vim using the <code>/</code> in command mode. To search, use <code>/string-to-match</code>.</p>
<p>In the command mode, type <code>:set hls</code> and press <code>enter</code>. Search using <code>/string-to-match</code>. This will highlight the searches.</p>
<p>Let's search a few strings:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392684097/11c4a45e-0698-4fb7-bef7-f193684ea21a.gif" alt="Highlighting searches in Vim" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>3. How to exit Vim</strong></p>
<p>First, move to command mode (by pressing escape twice) and then use these flags:</p>
<ul>
<li><p>Exit without saving → <code>:q!</code></p>
</li>
<li><p>Exit and save → <code>:wq!</code></p>
</li>
</ul>
<h4 id="heading-shortcuts-in-vim-making-editing-faster">Shortcuts in Vim: Making Editing Faster</h4>
<p>Note: All these shortcuts work in the command mode only.</p>
<ul>
<li><p><strong>Basic Navigation</strong></p>
<ul>
<li><p><code>h</code>: Move left</p>
</li>
<li><p><code>j</code>: Move down</p>
</li>
<li><p><code>k</code>: Move up</p>
</li>
<li><p><code>l</code>: Move right</p>
</li>
<li><p><code>0</code>: Move to the beginning of the line</p>
</li>
<li><p><code>$</code>: Move to the end of the line</p>
</li>
<li><p><code>gg</code>: Move to the beginning of the file</p>
</li>
<li><p><code>G</code>: Move to the end of the file</p>
</li>
<li><p><code>Ctrl+d</code>: Move half-page down</p>
</li>
<li><p><code>Ctrl+u</code>: Move half-page up</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>i</code>: Enter insert mode before the cursor</p>
</li>
<li><p><code>I</code>: Enter insert mode at the beginning of the line</p>
</li>
<li><p><code>a</code>: Enter insert mode after the cursor</p>
</li>
<li><p><code>A</code>: Enter insert mode at the end of the line</p>
</li>
<li><p><code>o</code>: Open a new line below the current line and enter insert mode</p>
</li>
<li><p><code>O</code>: Open a new line above the current line and enter insert mode</p>
</li>
<li><p><code>x</code>: Delete the character under the cursor</p>
</li>
<li><p><code>dd</code>: Delete the current line</p>
</li>
<li><p><code>yy</code>: Yank (copy) the current line (use this in visual mode)</p>
</li>
<li><p><code>p</code>: Paste below the cursor</p>
</li>
<li><p><code>P</code>: Paste above the cursor</p>
</li>
</ul>
</li>
<li><p><strong>Searching and Replacing</strong></p>
<ul>
<li><p><code>/</code>: Search for a pattern which will take you to its next occurrence</p>
</li>
<li><p><code>?</code>: Search for a pattern that will take you to its previous occurrence</p>
</li>
<li><p><code>n</code>: Repeat the last search in the same direction</p>
</li>
<li><p><code>N</code>: Repeat the last search in the opposite direction</p>
</li>
<li><p><code>:%s/old/new/g</code>: Replace all occurrences of <code>old</code> with <code>new</code> in the file</p>
</li>
</ul>
</li>
<li><p><strong>Exiting</strong></p>
<ul>
<li><p><code>:w</code>: Save the file but don't exit</p>
</li>
<li><p><code>:q</code>: Quit Vim (fails if there are unsaved changes)</p>
</li>
<li><p><code>:wq</code> or <code>:x</code>: Save and quit</p>
</li>
<li><p><code>:q!</code>: Quit without saving</p>
</li>
</ul>
</li>
<li><p><strong>Multiple Windows</strong></p>
<ul>
<li><p><code>:split</code> or <code>:sp</code>: Split the window horizontally</p>
</li>
<li><p><code>:vsplit</code> or <code>:vsp</code>: Split the window vertically</p>
</li>
<li><p><code>Ctrl+w followed by h/j/k/l</code>: Navigate between split windows</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-52-mastering-nano">5.2. Mastering Nano</h3>
<h4 id="heading-getting-started-with-nano-the-user-friendly-text-editor">Getting started with Nano: The user-friendly text editor</h4>
<p>Nano is a user-friendly text editor that is easy to use and is perfect for beginners. It is pre-installed on most Linux distributions.</p>
<p>To create a new file using Nano, use the following command:</p>
<pre><code class="lang-bash">nano
</code></pre>
<p>To start editing an existing file with Nano, use the following command:</p>
<pre><code class="lang-bash">nano filename
</code></pre>
<h4 id="heading-list-of-key-bindings-in-nano">List of key bindings in Nano</h4>
<p>Let's study the most important key bindings in Nano. You'll use the key bindings to perform various operations like saving, exiting, copying, pasting, and more.</p>
<p><strong>Write to a file and save</strong></p>
<p>Once you open Nano using the <code>nano</code> command, you can start writing text. To save the file, press <code>Ctrl+O</code>. You'll be prompted to enter the file name. Press <code>Enter</code> to save the file.</p>
<p><strong>Exit nano</strong></p>
<p>You can exit Nano by pressing <code>Ctrl+X</code>. If you have unsaved changes, Nano will prompt you to save the changes before exiting.</p>
<p><strong>Copying and pasting</strong></p>
<p>To select a region, use <code>ALT+A</code>. A marker will show. Use arrows to select the text. Once selected, exit the marker with with <code>ALT+^</code>.</p>
<p>To copy the selected text, press <code>Ctrl+K</code>. To paste the copied text, press <code>Ctrl+U</code>.</p>
<p><strong>Cutting and pasting</strong></p>
<p>Select the region with <code>ALT+A</code>. Once selected, cut the text with <code>Ctrl+K</code>. To paste the cut text, press <code>Ctrl+U</code>.</p>
<p><strong>Navigation</strong></p>
<p>Use <code>Alt \</code> to move to the beginning of the file.</p>
<p>Use <code>Alt /</code> to move to the end of the file.</p>
<p><strong>Viewing line numbers</strong></p>
<p>When you open a file with <code>nano -l filename</code>, you can view line numbers on the left side of the file.</p>
<p><strong>Searching</strong></p>
<p>You can search for a specific line number with <code>ALt + G</code>. Enter the line number to the prompt and press <code>Enter</code>.</p>
<p>You can also initiate search for a string with <code>CTRL + W</code> and press Enter. If you want to search backwards, you can press <code>Alt+W</code> after initiating the search with <code>Ctrl+W</code>.</p>
<h4 id="heading-summary-of-keybindings-in-nano">Summary of keybindings in Nano</h4>
<ul>
<li><p><strong>General</strong></p>
<ul>
<li><p><code>Ctrl+X</code>: Exit Nano (prompting to save if changes are made)</p>
</li>
<li><p><code>Ctrl+O</code>: Save the file</p>
</li>
<li><p><code>Ctrl+R</code>: Read a file into the current file</p>
</li>
<li><p><code>Ctrl+G</code>: Display the help text</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>Ctrl+K</code>: Cut the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+U</code>: Paste the contents of the cutbuffer into the current line</p>
</li>
<li><p><code>Alt+6</code>: Copy the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+J</code>: Justify the current paragraph</p>
</li>
</ul>
</li>
<li><p><strong>Navigation</strong></p>
<ul>
<li><p><code>Ctrl+A</code>: Move to the beginning of the line</p>
</li>
<li><p><code>Ctrl+E</code>: Move to the end of the line</p>
</li>
<li><p><code>Ctrl+C</code>: Display the current line number and file information</p>
</li>
<li><p><code>Ctrl+_</code> (<code>Ctrl+Shift+-</code>): Go to a specific line (and optionally, column) number</p>
</li>
<li><p><code>Ctrl+Y</code>: Scroll up one page</p>
</li>
<li><p><code>Ctrl+V</code>: Scroll down one page</p>
</li>
</ul>
</li>
<li><p><strong>Search and Replace</strong></p>
<ul>
<li><p><code>Ctrl+W</code>: Search for a string (then <code>Enter</code> to search again)</p>
</li>
<li><p><code>Alt+W</code>: Repeat the last search but in the opposite direction</p>
</li>
<li><p><code>Ctrl+\</code>: Search and replace</p>
</li>
</ul>
</li>
<li><p><strong>Miscellaneous</strong></p>
<ul>
<li><p><code>Ctrl+T</code>: Invoke the spell checker, if available</p>
</li>
<li><p><code>Ctrl+D</code>: Delete the character under the cursor (does not cut it)</p>
</li>
<li><p><code>Ctrl+L</code>: Refresh (redraw) the current screen</p>
</li>
<li><p><code>Alt+U</code>: Undo the last operation</p>
</li>
<li><p><code>Alt+E</code>: Redo the last undone operation</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-part-6-bash-scripting">Part 6: Bash Scripting</h2>
<h3 id="heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</h3>
<p>A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.</p>
<p>By saving commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.</p>
<h3 id="heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</h3>
<p>Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems.</p>
<p>Some advantages of shell scripting are:</p>
<ul>
<li><p><strong>Automation</strong>: Shell scripts allow you to automate repetitive tasks and processes, saving time and reducing the risk of errors that can occur with manual execution.</p>
</li>
<li><p><strong>Portability</strong>: Shell scripts can be run on various platforms and operating systems, including Unix, Linux, macOS, and even Windows through the use of emulators or virtual machines.</p>
</li>
<li><p><strong>Flexibility</strong>: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.</p>
</li>
<li><p><strong>Accessibility</strong>: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.</p>
</li>
<li><p><strong>Integration</strong>: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.</p>
</li>
<li><p><strong>Debugging</strong>: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.</p>
</li>
</ul>
<h3 id="heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</h3>
<p>The terms "shell" and "bash" are often used interchangeably. But there is a subtle difference between the two.</p>
<p>The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.</p>
<p>Till now, the commands that you have been entering were basically being entered in a "shell".</p>
<p>Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.</p>
<p>You can determine your shell type using the <code>ps</code> command:</p>
<pre><code class="lang-markdown">ps
<span class="hljs-section"># output:</span>

<span class="hljs-code">    PID TTY          TIME CMD
  20506 pts/0    00:00:00 bash &lt;--- the shell type
  20931 pts/0    00:00:00 ps</span>
</code></pre>
<p>In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.</p>
<p>Note: In this section, we will be using the "bash" shell.</p>
<h3 id="heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</h3>
<p><strong>Script naming conventions</strong></p>
<p>By naming convention, bash scripts end with <code>.sh</code>. However, bash scripts can run perfectly fine without the <code>sh</code> extension.</p>
<p><strong>Adding the Shebang</strong></p>
<p>Bash scripts start with a <code>shebang</code>. Shebang is a combination of <code>bash #</code> and <code>bang !</code> followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.</p>
<p>Below is an example of the shebang statement.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
</code></pre>
<p>You can find your bash shell path (which may vary from the above) using the command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">which</span> bash
</code></pre>
<p><strong>Creating your first bash script</strong></p>
<p>Our first script prompts the user to enter a path. In return, its contents will be listed.</p>
<p>Create a file named <code>run_all.sh</code> using any editor of your choice.</p>
<pre><code class="lang-bash">vim run_all.sh
</code></pre>
<p>Add the following commands in your file and save it:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
<span class="hljs-built_in">read</span> the_path

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
ls <span class="hljs-variable">$the_path</span>
</code></pre>
<p>Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.</p>
<pre><code class="lang-bash">  1 <span class="hljs-comment">#!/bin/bash</span>
  2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`
  3
  4 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
  5 <span class="hljs-built_in">read</span> the_path
  6
  7 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
  8 ls <span class="hljs-variable">$the_path</span>
</code></pre>
<ul>
<li><p>Line #1: The shebang (<code>#!/bin/bash</code>) points toward the bash shell path.</p>
</li>
<li><p>Line #2: The <code>echo</code> command displays the current date and time on the terminal. Note that the <code>date</code> is in backticks.</p>
</li>
<li><p>Line #4: We want the user to enter a valid path.</p>
</li>
<li><p>Line #5: The <code>read</code> command reads the input and stores it in the variable <code>the_path</code>.</p>
</li>
<li><p>line #8: The <code>ls</code> command takes the variable with the stored path and displays the current files and folders.</p>
</li>
</ul>
<p><strong>Executing the bash script</strong></p>
<p>To make the script executable, assign execution rights to your user using this command:</p>
<pre><code class="lang-bash">chmod u+x run_all.sh
</code></pre>
<p>Here,</p>
<ul>
<li><p><code>chmod</code> modifies the ownership of a file for the current user :<code>u</code>.</p>
</li>
<li><p><code>+x</code> adds the execution rights to the current user. This means that the user who is the owner can now run the script.</p>
</li>
<li><p><code>run_all.sh</code> is the file we wish to run.</p>
</li>
</ul>
<p>You can run the script using any of the mentioned methods:</p>
<ul>
<li><p><code>sh run_all.sh</code></p>
</li>
<li><p><code>bash run_all.sh</code></p>
</li>
<li><p><code>./run_all.sh</code></p>
</li>
</ul>
<p>Let's see it running in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/run-script-bash-2.gif" alt="Running a bash script" width="600" height="400" loading="lazy"></p>
<h3 id="heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</h3>
<h4 id="heading-comments-in-bash-scripting">Comments in bash scripting</h4>
<p>Comments start with a <code>#</code> in bash scripting. This means that any line that begins with a <code>#</code> is a comment and will be ignored by the interpreter.</p>
<p>Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.</p>
<p>These are examples of comments:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># This is an example comment</span>
<span class="hljs-comment"># Both of these lines will be ignored by the interpreter</span>
</code></pre>
<h4 id="heading-variables-and-data-types-in-bash">Variables and data types in Bash</h4>
<p>Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.</p>
<p>There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.</p>
<p>In Bash, you can use and set the variable values in the following ways:</p>
<ol>
<li>Assign the value directly:</li>
</ol>
<pre><code class="lang-bash">country=Netherlands
</code></pre>
<p>2.  Assign the value based on the output obtained from a program or command, using command substitution. Note that <code>$</code> is required to access an existing variable's value.</p>
<pre><code class="lang-bash">same_country=<span class="hljs-variable">$country</span>
</code></pre>
<p>This assigns the value of <code>country</code> to the new variable <code>same_country</code>.</p>
<p>To access the variable value, append <code>$</code> to the variable name.</p>
<pre><code class="lang-bash">country=Netherlands
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$country</span>
<span class="hljs-comment"># output</span>
Netherlands
new_country=<span class="hljs-variable">$country</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$new_country</span>
<span class="hljs-comment"># output</span>
Netherlands
</code></pre>
<p>Above, you can see an example of assigning and printing variable values.</p>
<h4 id="heading-variable-naming-conventions">Variable naming conventions</h4>
<p>In Bash scripting, the following are the variable naming conventions:</p>
<ol>
<li><p>Variable names should start with a letter or an underscore (<code>_</code>).</p>
</li>
<li><p>Variable names can contain letters, numbers, and underscores (<code>_</code>).</p>
</li>
<li><p>Variable names are case-sensitive.</p>
</li>
<li><p>Variable names should not contain spaces or special characters.</p>
</li>
<li><p>Use descriptive names that reflect the purpose of the variable.</p>
</li>
<li><p>Avoid using reserved keywords, such as <code>if</code>, <code>then</code>, <code>else</code>, <code>fi</code>, and so on as variable names.</p>
</li>
</ol>
<p>Here are some examples of valid variable names in Bash:</p>
<pre><code class="lang-bash">name
count
_var
myVar
MY_VAR
</code></pre>
<p>And here are some examples of invalid variable names:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># invalid variable names</span>

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)
</code></pre>
<p>Following these naming conventions helps make Bash scripts more readable and easier to maintain.</p>
<h4 id="heading-input-and-output-in-bash-scripts">Input and output in Bash scripts</h4>
<h4 id="heading-gathering-input">Gathering input</h4>
<p>In this section, we'll discuss some methods to provide input to our scripts.</p>
<ol>
<li>Reading the user input and storing it in a variable</li>
</ol>
<p>We can read the user input using the <code>read</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"What's your name?"</span>
<span class="hljs-built_in">read</span> entered_name
<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nWelcome to bash tutorial"</span> <span class="hljs-variable">$entered_name</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh.gif" alt="Reading the name from a script" width="600" height="400" loading="lazy"></p>
<p>2.  Reading from a file</p>
<p>This code reads each line from a file named <code>input.txt</code> and prints it to the terminal. We'll study while loops later in this section.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> <span class="hljs-built_in">read</span> line
<span class="hljs-keyword">do</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-variable">$line</span>
<span class="hljs-keyword">done</span> &lt; input.txt
</code></pre>
<p>3.  Command line arguments</p>
<p>In a bash script or function, <code>$1</code> denotes the initial argument passed, <code>$2</code> denotes the second argument passed, and so forth.</p>
<p>This script takes a name as a command-line argument and prints a personalized greeting.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$1</span>!"</span>
</code></pre>
<p>We have supplied <code>Zaira</code> as our argument to the script.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh-1.gif" alt="Providing arguments to the bash script" width="600" height="400" loading="lazy"></p>
<h4 id="heading-displaying-output">Displaying output</h4>
<p>Here we'll discuss some methods to receive output from the scripts.</p>
<ol>
<li>Printing to the terminal:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, World!"</span>
</code></pre>
<p>This prints the text "Hello, World!" to the terminal.</p>
<p>2.  Writing to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"This is some text."</span> &gt; output.txt
</code></pre>
<p>This writes the text "This is some text." to a file named <code>output.txt</code>. Note that the <code>&gt;</code> operator overwrites a file if it already has some content.</p>
<p>3.  Appending to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"More text."</span> &gt;&gt; output.txt
</code></pre>
<p>This appends the text "More text." to the end of the file <code>output.txt</code>.</p>
<p>4.  Redirecting output:</p>
<pre><code class="lang-bash">ls &gt; files.txt
</code></pre>
<p>This lists the files in the current directory and writes the output to a file named <code>files.txt</code>. You can redirect output of any command to a file this way.</p>
<p>You'll learn about output redirection in detail in section 8.5.</p>
<h4 id="heading-conditional-statements-ifelse">Conditional statements (if/else)</h4>
<p>Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including <code>if</code>, <code>if-else</code>, <code>if-elif-else</code>, and nested conditionals.</p>
<p><strong>Syntax</strong>:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [[ condition ]];
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">elif</span> [[ condition ]]; <span class="hljs-keyword">then</span>
    statement 
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<h4 id="heading-syntax-of-bash-conditional-statements">Syntax of bash conditional statements</h4>
<p>We can use logical operators such as AND <code>-a</code> and OR <code>-o</code> to make comparisons that have more significance.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -gt 60 -a <span class="hljs-variable">$b</span> -lt 100 ]
</code></pre>
<p>This statement checks if both conditions are <code>true</code>: <code>a</code> is greater than <code>60</code> AND <code>b</code> is less than <code>100</code>.</p>
<p>Let's see an example of a Bash script that uses <code>if</code>, <code>if-else</code>, and <code>if-elif-else</code> statements to determine if a user-inputted number is positive, negative, or zero:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Script to determine if a number is positive, negative, or zero</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Please enter a number: "</span>
<span class="hljs-built_in">read</span> num

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$num</span> -gt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is positive"</span>
<span class="hljs-keyword">elif</span> [ <span class="hljs-variable">$num</span> -lt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is negative"</span>
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is zero"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p>The script first prompts the user to enter a number. Then, it uses an <code>if</code> statement to check if the number is greater than <code>0</code>. If it is, the script outputs that the number is positive. If the number is not greater than <code>0</code>, the script moves on to the next statement, which is an <code>if-elif</code> statement.</p>
<p>Here, the script checks if the number is less than <code>0</code>. If it is, the script outputs that the number is negative.</p>
<p>Finally, if the number is neither greater than <code>0</code> nor less than <code>0</code>, the script uses an <code>else</code> statement to output that the number is zero.</p>
<p>Seeing it in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/test-odd.gif" alt="Checking if a number is even or odd" width="600" height="400" loading="lazy"></p>
<h4 id="heading-looping-and-branching-in-bash">Looping and branching in Bash</h4>
<p><strong>While loop</strong></p>
<p>While loops check for a condition and loop until the condition remains <code>true</code>. We need to provide a counter statement that increments the counter to control loop execution.</p>
<p>In the example below, <code>(( i += 1 ))</code> is the counter statement that increments the value of <code>i</code>. The loop will run exactly 10 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
i=1
<span class="hljs-keyword">while</span> [[ <span class="hljs-variable">$i</span> -le 10 ]] ; <span class="hljs-keyword">do</span>
   <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$i</span>"</span>
  (( i += 1 ))
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-187.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>For loop</strong></p>
<p>The <code>for</code> loop, just like the <code>while</code> loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.</p>
<p>In the example below, the loop will iterate 5 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> {1..5}
<span class="hljs-keyword">do</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$i</span>
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-186.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>Case statements</strong></p>
<p>In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">case</span> expression <span class="hljs-keyword">in</span>
    pattern1)
        <span class="hljs-comment"># code to execute if expression matches pattern1</span>
        ;;
    pattern2)
        <span class="hljs-comment"># code to execute if expression matches pattern2</span>
        ;;
    pattern3)
        <span class="hljs-comment"># code to execute if expression matches pattern3</span>
        ;;
    *)
        <span class="hljs-comment"># code to execute if none of the above patterns match expression</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against.</p>
<p>The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.</p>
<p>Let's see an example:</p>
<pre><code class="lang-bash">fruit=<span class="hljs-string">"apple"</span>

<span class="hljs-keyword">case</span> <span class="hljs-variable">$fruit</span> <span class="hljs-keyword">in</span>
    <span class="hljs-string">"apple"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a red fruit."</span>
        ;;
    <span class="hljs-string">"banana"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a yellow fruit."</span>
        ;;
    <span class="hljs-string">"orange"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is an orange fruit."</span>
        ;;
    *)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Unknown fruit."</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>In this example, since the value of <code>fruit</code> is <code>apple</code>, the first pattern matches, and the block of code that echoes <code>This is a red fruit.</code> is executed. If the value of <code>fruit</code> were instead <code>banana</code>, the second pattern would match and the block of code that echoes <code>This is a yellow fruit.</code> would execute, and so on.</p>
<p>If the value of <code>fruit</code> does not match any of the specified patterns, the default case is executed, which echoes <code>Unknown fruit.</code></p>
<h2 id="heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</h2>
<p>Linux comes with several built-in programs. But you might need to install new programs based on your needs. You might also need to upgrade the existing applications.</p>
<h3 id="heading-71-packages-and-package-management">7.1. Packages and Package Management</h3>
<h4 id="heading-what-is-a-package">What is a package?</h4>
<p>A package is a collection of files that are bundled together. These files are essential for a particular program to run. These files contain the program's executable files, libraries, and other resources.</p>
<p>In addition to the files required for the program to run, packages also contain installation scripts, which copy the files to where they are needed. A program may contain many files and dependencies. With packages, it is easier to manage all the files and dependencies at once.</p>
<h4 id="heading-what-is-the-difference-between-source-and-binary">What is the difference between source and binary?</h4>
<p>Programmers write source code in a programming language. This source code is then compiled into machine code that the computer can understand. The compiled code is called binary code.</p>
<p>When you download a package, you can either get the <em>source code</em> or the <em>binary code.</em> The source code is the human-readable code that can be compiled into binary code. The binary code is the compiled code that the computer can understand.</p>
<p>Source packages can be used with any type of machine if the source code is compiled properly. Binary, on the other hand, is compiled code that is specific to a particular type of machine or architecture.</p>
<p>You can find the architecture of your machine using the <code>uname -m</code> command.</p>
<pre><code class="lang-bash">uname -m
<span class="hljs-comment"># output</span>
x86_64
</code></pre>
<h4 id="heading-package-dependencies">Package dependencies</h4>
<p>Programs often share files. Instead of including these files in each package, a separate package can provide them for all programs.</p>
<p>To install a program that needs these files, you must also install the package containing them. This is called a package dependency. Specifying dependencies makes packages smaller and simpler by reducing duplicates.</p>
<p>When you install a program, its dependencies must also be installed. Most required dependencies are usually already installed, but a few extra ones might be needed. So, don't be surprised if several other packages are installed along with your chosen package. These are the necessary dependencies.</p>
<h4 id="heading-package-managers">Package managers</h4>
<p>Linux offers a comprehensive package management system for installing, upgrading, configuring, and removing software.</p>
<p>With package management, you can get access to an organized base of thousands of software packages along with having the ability to resolve dependencies and check for software updates.</p>
<p>Packages can be managed using either command-line utilities that can be easily automated by system administrators, or through a graphical interface.</p>
<h4 id="heading-software-channelsrepositories">Software channels/repositories</h4>
<p>⚠️ Package management is different for different distros. Here, we are using Ubuntu.</p>
<p>Installing software is a bit different in Linux as compared to Windows and Mac.</p>
<p>Linux uses repositories to store software packages. A repository is a collection of software packages that are available for installation via a package manager.</p>
<p>A package manager also stores an index of all of the packages available from a repo. Sometimes the index is rebuilt to ensure that it is up to date and to know which packages have been upgraded or added to the channel since it last checked.</p>
<p>The generic process of downloading software from a repo looks something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313472889/f4961606-b9c4-4ed7-8edc-61e0fc6908e4.png" alt="Rrocess of downloading software from a remote repo" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If we talk specifically about Ubuntu,</p>
<ol>
<li><p>Index is fetched using <code>apt update.</code> (<code>apt</code> is explained in next section).</p>
</li>
<li><p>Required files/ dependencies requested according to index using <code>apt install</code></p>
</li>
<li><p>Packages and dependencies installed locally.</p>
</li>
<li><p>Update dependencies and packages when required using <code>apt update</code> and <code>apt upgrade</code></p>
</li>
</ol>
<p>On Debian-based distros, you can file the list of repos (repositories) in <code>/etc/apt/sources.list</code>.</p>
<h3 id="heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</h3>
<p>The <code>apt</code> command is a powerful command-line tool, which works with Ubuntu’s "Advanced Packaging Tool (APT)".</p>
<p><code>apt</code>, along with the commands bundled with it, provides the means to install new software packages, upgrade existing software packages, update the package list index, and even upgrade the entire Ubuntu system.</p>
<p>To view the logs of the installation using <code>apt</code>, you can view the <code>/var/log/dpkg.log</code> file.</p>
<p>Following are the uses of the <code>apt</code> command:</p>
<h4 id="heading-installing-packages">Installing packages</h4>
<p>For example, to install the <code>htop</code> package, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt install htop
</code></pre>
<h4 id="heading-updating-the-package-list-index">Updating the package list index</h4>
<p>The package list index is a list of all the packages available in the repositories. To update the local package list index, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt update
</code></pre>
<h4 id="heading-upgrading-the-packages">Upgrading the packages</h4>
<p>Installed packages on your system can get updates containing bug fixes, security patches, and new features.</p>
<p>To upgrade the packages, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt upgrade
</code></pre>
<h4 id="heading-removing-packages">Removing packages</h4>
<p>To remove a package, like <code>htop</code>, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt remove htop
</code></pre>
<h3 id="heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</h3>
<p>If you are not comfortable with the command line, you can use a GUI application to install packages. You can achieve the same results as the command line, but with a graphical interface.</p>
<p>Synaptic is a GUI package management application that helps in listing the installed packages, their status, pending updates, and so on. It offers custom filters to help you narrow down the search results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313599636/0f362ed7-c371-4a58-96c2-c359178cdbd9.png" alt="0f362ed7-c371-4a58-96c2-c359178cdbd9" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>You can also right-click on a package and view further details like the dependencies, maintainer, size, and the installed files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313607397/33b7ad76-2492-4805-8133-35c8cd3c4a0a.png" alt="View a package's detail" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</h3>
<p>You may want to install a package you have downloaded from a website, rather than from a software repository. These packages are called <code>.deb</code> files.</p>
<p><strong>Using</strong><code>dpkg</code><strong>to install packages:</strong><code>dpkg</code> is a command-line tool used to install packages. To install a package with <strong>dpkg</strong>, open the Terminal and type the following:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> directory
sudo dpkg -i package_name.deb
</code></pre>
<p>Note: Replace "directory" with the directory where the package is stored and "package_name" with the filename of the package.</p>
<p>Alternatively, you can right-click, select "Open With Other Application," and choose a GUI app of your choice.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322161581/f16d83ac-ca9a-4502-a80c-e6a25dee5c68.png" alt="Installing a software using an app" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> In Ubuntu, you can see a list of installed packages with <code>dpkg --list</code>.</p>
<h2 id="heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</h2>
<h3 id="heading-81-user-management">8.1. User Management</h3>
<p>There can be multiple users with varying levels of access in a system. In Linux, the root user has the highest level of access and can perform any operation on the system. Regular users have limited access and can only perform operations they have been granted permission to do.</p>
<h4 id="heading-what-is-a-user">What is a user?</h4>
<p>A user account provides separation between different people and programs that can run commands.</p>
<p>Humans identify users by a name, as names are easy to work with. But the system identifies users by a unique number called the user ID (UID).</p>
<p>When human users log in using the provided username, they have to use a password to authorize themselves.</p>
<p>User accounts form the foundations of system security. File ownership is also associated with user accounts and it enforces access control to the files. Every process has an associated user account that provides a layer of control for the admins.</p>
<p>There are three main types of user accounts:</p>
<ol>
<li><p><strong>Superuser</strong>: The superuser has complete access to the system. The name of the superuser is <code>root</code>. It has a <code>UID</code> of 0.</p>
</li>
<li><p><strong>System user</strong>: The system user has user accounts that are used to run system services. These accounts are used to run system services and are not meant for human interaction.</p>
</li>
<li><p><strong>Regular user</strong>: Regular users are human users who have access to the system.</p>
</li>
</ol>
<p>The <code>id</code> command displays the user ID and group ID of the current user.</p>
<pre><code class="lang-bash">id
uid=1000(john) gid=1000(john) groups=1000(john),4(adm),24(cdrom),27(sudo),30(dip)... output truncated
</code></pre>
<p>To view the basic information of another user, pass the username as an argument to the <code>id</code> command.</p>
<pre><code class="lang-bash">id username
</code></pre>
<p>To view user-related information for processes, use the <code>ps</code> command with the <code>-u</code> flag.</p>
<pre><code class="lang-bash">ps -u
<span class="hljs-comment"># Output</span>
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1  16968  3920 ?        Ss   18:45   0:00 /sbin/init splash
root         2  0.0  0.0      0     0 ?        S    18:45   0:00 [kthreadd]
</code></pre>
<p>By default, systems use the <code>/etc/passwd</code> file to store user information.</p>
<p>Here is a line from the <code>/etc/passwd</code> file:</p>
<pre><code class="lang-bash">root:x:0:0:root:/root:/bin/bash
</code></pre>
<p>The <code>/etc/passwd</code> file contains the following information about each user:</p>
<ol>
<li><p>Username: <code>root</code> – The username of the user account.</p>
</li>
<li><p>Password: <code>x</code> – The password in encrypted format for the user account that is stored in the <code>/etc/shadow</code> file for security reasons.</p>
</li>
<li><p>User ID (UID): <code>0</code> – The unique numerical identifier for the user account.</p>
</li>
<li><p>Group ID (GID): <code>0</code> – The primary group identifier for the user account.</p>
</li>
<li><p>User Info: <code>root</code> – The real name for the user account.</p>
</li>
<li><p>Home directory: <code>/root</code> – The home directory for the user account.</p>
</li>
<li><p>Shell: <code>/bin/bash</code> – The default shell for the user account. A system user might use <code>/sbin/nologin</code> if interactive logins are not allowed for that user.</p>
</li>
</ol>
<h4 id="heading-what-is-a-group">What is a group?</h4>
<p>A group is a collection of user accounts that share access and resources. Groups have group names to identify them. The system identifies groups by a unique number called the group ID (GID).</p>
<p>By default, the information about groups is stored in the <code>/etc/group</code> file.</p>
<p>Here is an entry from the <code>/etc/group</code> file:</p>
<pre><code class="lang-bash">adm:x:4:syslog,john
</code></pre>
<p>Here is the breakdown of the fields in the given entry:</p>
<ol>
<li><p>Group name: <code>adm</code> – The name of the group.</p>
</li>
<li><p>Password: <code>x</code> – The password for the group is stored in the <code>/etc/gshadow</code> file for security reasons. The password is optional and appears empty if not set.</p>
</li>
<li><p>Group ID (GID): <code>4</code> – The unique numerical identifier for the group.</p>
</li>
<li><p>Group members: <code>syslog,john</code> – The list of usernames that are members of the group. In this case, the group <code>adm</code> has two members: <code>syslog</code> and <code>john</code>.</p>
</li>
</ol>
<p>In this specific entry, the group name is <code>adm</code>, the group ID is <code>4</code>, and the group has two members: <code>syslog</code> and <code>john</code>. The password field is typically set to <code>x</code> to indicate that the group password is stored in the <code>/etc/gshadow</code> file.</p>
<p>The groups are further divided into '<em>primary'</em> and '<em>supplementary'</em> groups.</p>
<ul>
<li><p>Primary Group: Each user is assigned one primary group by default. This group usually has the same name as the user and is created when the user account is made. Files and directories created by the user are typically owned by this primary group.</p>
</li>
<li><p>Supplementary Groups: These are extra groups a user can belong to in addition to their primary group. Users can be members of multiple supplementary groups. These groups let a user have permissions for resources shared among those groups. They help provide access to shared resources without affecting the system’s file permissions and keeping the security intact. While a user must belong to one primary group, belonging to supplementary groups is optional.</p>
</li>
</ul>
<h4 id="heading-access-control-finding-and-understanding-file-permission">Access control: finding and understanding file permission</h4>
<p>File ownership can be viewed using the <code>ls -l</code> command. The first column in the output of the <code>ls -l</code> command shows the permissions of the file. Other columns show the owner of the file and the group that the file belongs to.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-146.png" alt="Detailed output of ls -l" width="600" height="400" loading="lazy"></p>
<p>Let's have a closer look into the <code>mode</code> column:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-147.png" alt="Permission classes and file types" width="600" height="400" loading="lazy"></p>
<p><strong>Mode</strong> defines two things:</p>
<ul>
<li><p><strong>File type:</strong> File type defines the type of the file. For regular files that contain simple data it is blank <code>-</code>. For other special file types the symbol is different. For a directory which is a special file, it is <code>d</code>. Special files are treated differently by the OS.</p>
</li>
<li><p><strong>Permission classes:</strong> The next set of characters define the permissions for user, group, and others respectively.<br>  – <strong>User</strong>: This is the owner of a file and owner of the file belongs to this class.<br>  – <strong>Group</strong>: The members of the file’s group belong to this class<br>  – <strong>Other</strong>: Any users that are not part of the user or group classes belong to this class.</p>
</li>
</ul>
<p>💡<strong>Tip:</strong> Directory ownership can be viewed using the <code>ls -ld</code> command.</p>
<h5 id="heading-how-to-read-symbolic-permissions-or-the-rwx-permissions">How to Read Symbolic Permissions or the <code>rwx</code> permissions</h5>
<p>The <code>rwx</code> representation is known as the Symbolic representation of permissions. In the set of permissions,</p>
<ul>
<li><p><code>r</code> stands for <strong>read</strong>. It is indicated in the first character of the triad.</p>
</li>
<li><p><code>w</code> stands for <strong>write</strong>. It is indicated in the second character of the triad.</p>
</li>
<li><p><code>x</code> stands for <strong>execution</strong>. It is indicated in the third character of the triad.</p>
</li>
</ul>
<p><strong>Read:</strong></p>
<p>For regular files, read permissions allow the file to be opened and read only. Users can't modify the file.</p>
<p>Similarly for directories, read permissions allow the listing of directory content without any modification in the directory.</p>
<p><strong>Write:</strong></p>
<p>When files have write permissions, the user can modify (edit, delete) the file and save it.</p>
<p>For folders, write permissions enable a user to modify its contents (create, delete, and rename the files inside it), and modify the contents of files that the user has write permissions to.</p>
<p><strong>Examples of permissions in Linux</strong></p>
<p>Now that we know how to read permissions, let's see some examples.</p>
<ul>
<li><p><code>-rwx------</code>: A file that is only accessible and executable by its owner.</p>
<p>  <code>-rw-rw-r--</code>: A file that is open to modification by its owner and group but not by others.</p>
</li>
<li><p><code>drwxrwx---</code>: A directory that can be modified by its owner and group.</p>
</li>
</ul>
<p><strong>Execute:</strong></p>
<p>For files, execute permissions allows the user to run an executable script. For directories, the user can access them, and access details about files in the directory.</p>
<h5 id="heading-how-to-change-file-permissions-and-ownership-in-linux-using-chmod-and-chown">How to Change File Permissions and Ownership in Linux using <code>chmod</code> and <code>chown</code></h5>
<p>Now that we know the basics of ownerships and permissions, let's see how we can modify permissions using the <code>chmod</code> command.</p>
<p><strong>Syntax of</strong><code>chmod</code>:</p>
<pre><code class="lang-bash">chmod permissions filename
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>permissions</code> can be read, write, execute or a combination of them.</p>
</li>
<li><p><code>filename</code> is the name of the file for which the permissions need to change. This parameter can also be a list if files to change permissions in bulk.</p>
</li>
</ul>
<p>We can change permissions using two modes:</p>
<ol>
<li><p><strong>Symbolic mode</strong>: this method uses symbols like <code>u</code>, <code>g</code>, <code>o</code> to represent users, groups, and others. Permissions are represented as  <code>r, w, x</code> for read, write, and execute, respectively. You can modify permissions using +, - and =.</p>
</li>
<li><p><strong>Absolute mode</strong>: this method represents permissions as 3-digit octal numbers ranging from 0-7.</p>
</li>
</ol>
<p>Now, let's see them in detail.</p>
<h5 id="heading-how-to-change-permissions-using-symbolic-mode">How to Change Permissions using Symbolic Mode</h5>
<p>The table below summarize the user representation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>USER REPRESENTATION</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>u</td><td>user/owner</td></tr>
<tr>
<td>g</td><td>group</td></tr>
<tr>
<td>o</td><td>other</td></tr>
</tbody>
</table>
</div><p>We can use mathematical operators to add, remove, and assign permissions. The table below shows the summary:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>OPERATOR</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>+</td><td>Adds a permission to a file or directory</td></tr>
<tr>
<td>–</td><td>Removes the permission</td></tr>
<tr>
<td>\=</td><td>Sets the permission if not present before. Also overrides the permissions if set earlier.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p>Suppose I have a script and I want to make it executable for the owner of the file <code>zaira</code>.</p>
<p>Current file permissions are as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-161.png" alt="image-161" width="600" height="400" loading="lazy"></p>
<p>Let's split the permissions like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-160.png" alt="Splitting file permissions" width="600" height="400" loading="lazy"></p>
<p>To add execution rights (<code>x</code>) to owner (<code>u</code>) using symbolic mode, we can use the command below:</p>
<pre><code class="lang-bash">chmod u+x mymotd.sh
</code></pre>
<p><strong>Output:</strong></p>
<p>Now, we can see that the execution permissions have been added for owner <code>zaira</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-162.png" alt="Permission updated" width="600" height="400" loading="lazy"></p>
<p><strong>Additional examples for changing permissions via symbolic method:</strong></p>
<ul>
<li><p>Removing <code>read</code> and <code>write</code> permission for <code>group</code> and <code>others</code>: <code>chmod go-rw</code>.</p>
</li>
<li><p>Removing <code>read</code> permissions for <code>others</code>: <code>chmod o-r</code>.</p>
</li>
<li><p>Assigning <code>write</code> permission to <code>group</code> and overriding existing permission: <code>chmod g=w</code>.</p>
</li>
</ul>
<h5 id="heading-how-to-change-permissions-using-absolute-mode">How to Change Permissions using Absolute Mode</h5>
<p>Absolute mode uses numbers to represent permissions and mathematical operators to modify them.</p>
<p>The below table shows how we can assign relevant permissions:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>PROVIDE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>add 4</td></tr>
<tr>
<td>write</td><td>add 2</td></tr>
<tr>
<td>execute</td><td>add 1</td></tr>
</tbody>
</table>
</div><p>Permissions can be revoked using subtraction. The below table shows how you can remove relevant permissions.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>REVOKE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>subtract 4</td></tr>
<tr>
<td>write</td><td>subtract 2</td></tr>
<tr>
<td>execute</td><td>subtract 1</td></tr>
</tbody>
</table>
</div><p><strong>Example</strong>:</p>
<ul>
<li>Set <code>read</code> (add 4) for <code>user</code>, <code>read</code> (add 4) and <code>execute</code> (add 1) for group, and only <code>execute</code> (add 1) for others.</li>
</ul>
<p><code>chmod 451 file-name</code></p>
<p>This is how we performed the calculation:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-163.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<p>Note that this is the same as <code>r--r-x--x</code>.</p>
<ul>
<li>Remove <code>execution</code> rights from <code>other</code> and <code>group</code>.</li>
</ul>
<p>To remove execution from <code>other</code> and <code>group</code>, subtract 1 from the execute part of last 2 octets.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-164.png" alt="Calculation breakdown for removing permissions" width="600" height="400" loading="lazy"></p>
<ul>
<li>Assign <code>read</code>, <code>write</code> and <code>execute</code> to <code>user</code>, <code>read</code> and <code>execute</code> to <code>group</code> and only <code>read</code> to others.</li>
</ul>
<p>This would be the same as <code>rwxr-xr--</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-165.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-ownership-using-the-chown-command">How to Change Ownership using the <code>chown</code> Command</h5>
<p>Next, we will learn how to change the ownership of a file. You can change the ownership of a file or folder using the <code>chown</code> command. In some cases, changing ownership requires <code>sudo</code> permissions.</p>
<p>Syntax of <code>chown</code>:</p>
<pre><code class="lang-bash">chown user filename
</code></pre>
<h5 id="heading-how-to-change-user-ownership-with-chown">How to change user ownership with <code>chown</code></h5>
<p>Let's transfer the ownership from user <code>zaira</code> to user <code>news</code>.</p>
<p><code>chown news mymotd.sh</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-167.png" alt="view current owner" width="600" height="400" loading="lazy"></p>
<p>Command to change ownership: <code>sudo chown news mymotd.sh</code>.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-168.png" alt="Ownership changed" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-user-and-group-ownership-simultaneously">How to change user and group ownership simultaneously</h5>
<p>We can also use <code>chown</code> to change user and group simultaneously.</p>
<pre><code class="lang-bash">chown user:group filename
</code></pre>
<h5 id="heading-how-to-change-directory-ownership">How to change directory ownership</h5>
<p>You can change ownership recursively for contents in a directory. The example below changes the ownership of the <code>/opt/script</code> folder to allow user <code>admin</code>.</p>
<pre><code class="lang-bash">chown -R admin /opt/script
</code></pre>
<h5 id="heading-how-to-change-group-ownership">How to change group ownership</h5>
<p>In case we only need to change the group owner, we can use <code>chown</code> by preceding the group name by a colon <code>:</code></p>
<pre><code class="lang-bash">chown :admins /opt/script
</code></pre>
<h5 id="heading-how-to-switch-between-users">How to switch between users</h5>
<p>You can switch between users using the <code>su</code> command.</p>
<pre><code class="lang-bash">[user01@host ~]$ su user02
Password:
[user02@host ~]$
</code></pre>
<h5 id="heading-how-to-gain-superuser-access">How to gain superuser access</h5>
<p>The superuser or the root user has the highest level of access on a Linux system. The root user can perform any operation on the system. The root user can access all files and directories, install and remove software, and modify or override system configurations.</p>
<p>With great power comes great responsibility. If the root user is compromised, someone can gain complete control over the system. It is advised to use the root user account only when necessary.</p>
<p>If you omit the username, the <code>su</code> command switches to the root user account by default.</p>
<pre><code class="lang-bash">[user01@host ~]$ su
Password:
[root@host ~]<span class="hljs-comment">#</span>
</code></pre>
<p>Another variation of the <code>su</code> command is <code>su -</code>. The <code>su</code> command switches to the root user account but does not change the environment variables. The <code>su -</code> command switches to the root user account and changes the environment variables to those of the target user.</p>
<h5 id="heading-running-commands-with-sudo">Running commands with sudo</h5>
<p>To run commands as the <code>root</code> user without switching to the <code>root</code> user account, you can use the <code>sudo</code> command. The <code>sudo</code> command allows you to run commands with elevated privileges.</p>
<p>Running commands with <code>sudo</code> is a safer option rather than running the commands as the <code>root</code> user. This is because, only a specific set of users can be granted permission to run commands with <code>sudo</code>. This is defined in the <code>/etc/sudoers</code> file.</p>
<p>Also, <code>sudo</code> logs all commands that are run with it, providing an audit trail of who ran which commands and when.</p>
<p>In Ubuntu, you can find the audit logs here:</p>
<pre><code class="lang-bash">cat /var/<span class="hljs-built_in">log</span>/auth.log | grep sudo
</code></pre>
<p>For a user that does not have access to <code>sudo</code>, it gets flagged in logs and prompts a message like this:</p>
<pre><code class="lang-bash">user01 is not <span class="hljs-keyword">in</span> the sudoers file.  This incident will be reported.
</code></pre>
<h4 id="heading-managing-local-user-accounts">Managing local user accounts</h4>
<h5 id="heading-creating-users-from-the-command-line">Creating users from the command line</h5>
<p>The command used to add a new user is:</p>
<pre><code class="lang-bash">sudo useradd username
</code></pre>
<p>This command sets up a user's home directory and creates a private group designated by the user's username. Currently, the account lacks a valid password, preventing the user from logging in until a password is created.</p>
<h5 id="heading-modifying-existing-users">Modifying existing users</h5>
<p>The <code>usermod</code> command is used to modify existing users. Here are some of the common options used with the <code>usermod</code> command:</p>
<p>Here are some examples of the <code>usermod</code> command in Linux:</p>
<ol>
<li><p><strong>Change a user's login name:</strong></p>
<pre><code class="lang-bash"> sudo usermod -l newusername oldusername
</code></pre>
</li>
<li><p><strong>Change a user's home directory:</strong></p>
<pre><code class="lang-bash"> sudo usermod -d /new/home/directory -m username
</code></pre>
</li>
<li><p><strong>Add a user to a supplementary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -aG groupname username
</code></pre>
</li>
<li><p><strong>Change a user's shell:</strong></p>
<pre><code class="lang-bash"> sudo usermod -s /bin/bash username
</code></pre>
</li>
<li><p><strong>Lock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -L username
</code></pre>
</li>
<li><p><strong>Unlock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -U username
</code></pre>
</li>
<li><p><strong>Set an expiration date for a user account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -e YYYY-MM-DD username
</code></pre>
</li>
<li><p><strong>Change a user's user ID (UID):</strong></p>
<pre><code class="lang-bash"> sudo usermod -u newUID username
</code></pre>
</li>
<li><p><strong>Change a user's primary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -g newgroup username
</code></pre>
</li>
<li><p><strong>Remove a user from a supplementary group:</strong></p>
<pre><code class="lang-bash">sudo gpasswd -d username groupname
</code></pre>
</li>
</ol>
<h5 id="heading-deleting-users">Deleting users</h5>
<p>The <code>userdel</code> command is used to delete a user account and related files from the system.</p>
<ul>
<li><p><code>sudo userdel username</code>: removes the user's details from <code>/etc/passwd</code> but keeps the user's home directory.</p>
</li>
<li><p>The <code>sudo userdel -r username</code> command removes the user's details from <code>/etc/passwd</code> and also deletes the user's home directory.</p>
</li>
</ul>
<h5 id="heading-changing-user-passwords">Changing user passwords</h5>
<p>The <code>passwd</code> command is used to change a user's password.</p>
<ul>
<li><code>sudo passwd username</code>: sets the initial password or changes the existing password of username. It is also used to change the password of the currently logged in user.</li>
</ul>
<h3 id="heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</h3>
<p>Accessing remote servers is one of the essential tasks for system administrators. You can connect to different servers or access databases through your local machine and execute commands, all using SSH.</p>
<p><strong>What is the SSH protocol?</strong></p>
<p>SSH stands for Secure Shell. It is a cryptographic network protocol that allows secure communication between two systems.</p>
<p>The default port for SSH is <code>22</code>.</p>
<p>The two participants while communicating via SSH are:</p>
<ul>
<li><p>The server: the machine that you want access to.</p>
</li>
<li><p>The client: The system that you are accessing the server from.</p>
</li>
</ul>
<p>Connection to a server follows these steps:</p>
<ol>
<li><p>Initiate Connection: The client sends a connection request to the server.</p>
</li>
<li><p>Exchange of Keys: The server sends its public key to the client. Both agree on the encryption methods to use.</p>
</li>
<li><p>Session Key Generation: The client and server use the Diffie-Hellman key exchange to create a shared session key.</p>
</li>
<li><p>Client Authentication: The client logs in to the server using a password, private key, or another method.</p>
</li>
<li><p>Secure Communication: After authentication, the client and server communicate securely with encryption.</p>
</li>
</ol>
<p><strong>How to connect to a remote server using SSH?</strong></p>
<p>The <code>ssh</code> command is a built-in utility in Linux and also the default one. It makes accessing servers quite easy and secure.</p>
<p>Here, we are talking about how the client would make a connection to the server.</p>
<p>Prior to connecting to a server, you need to have the following information:</p>
<ul>
<li><p>The IP address or the domain name of the server.</p>
</li>
<li><p>The username and password of the server.</p>
</li>
<li><p>The port number that you have access to in the server.</p>
</li>
</ul>
<p>The basic syntax of the <code>ssh</code> command is:</p>
<pre><code class="lang-bash">ssh username@server_ip
</code></pre>
<p>For example, if your username is <code>john</code> and the server IP is <code>192.168.1.10</code>, the command would be:</p>
<pre><code class="lang-bash">ssh john@192.168.1.10
</code></pre>
<p>After that, you'll be prompted to enter the secret password. Your screen will look similar to this:</p>
<pre><code class="lang-bash">john@192.168.1.10<span class="hljs-string">'s password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Jun  5 10:17:32 UTC 2024

  System load:  0.08               Processes:           122
  Usage of /:   12.3% of 19.56GB   Users logged in:     1
  Memory usage: 53%                IP address for eth0: 192.168.1.10
  Swap usage:   0%

Last login: Fri Jun  5 09:34:56 2024 from 192.168.1.2
john@hostname:~$ # start entering commands</span>
</code></pre>
<p>Now you can execute the relevant commands on the server <code>192.168.1.10</code>.</p>
<p>⚠️ The default port for ssh is <code>22</code> but it is also vulnerable, as hackers will likely attempt here first. Your server can expose another port and share the access with you. To connect to a different port, use the <code>-p</code> flag.</p>
<pre><code class="lang-bash">ssh -p port_number username@server_ip
</code></pre>
<h3 id="heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</h3>
<p>Log files, when configured, are generated by your system for a variety of useful reasons. They can be used to track system events, monitor system performance, and troubleshoot issues. They are specifically useful for system administrators where they can track application errors, network events, and user activity.</p>
<p>Here is an example of a log file:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sample log file</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 DEBUG Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 WARN Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 DEBUG API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
</code></pre>
<p>A log file usually contains the following columns:</p>
<ul>
<li><p>Timestamp: The date and time when the event occurred.</p>
</li>
<li><p>Log Level: The severity of the event (INFO, DEBUG, WARN, ERROR).</p>
</li>
<li><p>Component: The component of the system that generated the event (Startup, Config, Database, User, Security, Network, Email, API, Session, Shutdown).</p>
</li>
<li><p>Message: A description of the event that occurred.</p>
</li>
<li><p>Additional Information: Additional information related to the event.</p>
</li>
</ul>
<p>In real-time systems, log files tend to be thousands of lines long and are generated every second. They can be very wordy depending on the configuration. Every column in a log file is a piece of information that can be used to track down issues. This makes log files difficult to read and understand manually.</p>
<p>This is where log parsing comes in. Log parsing is the process of extracting useful information from log files. It involves breaking down the log files into smaller, more manageable pieces, and extracting the relevant information.</p>
<p>The filtered information can also be useful for creating alerts, reports, and dashboards.</p>
<p>In this section, you will explore some techniques for parsing log files in Linux.</p>
<h4 id="heading-text-extraction-using-grep">Text extraction using <code>grep</code></h4>
<p>Grep is a built-in bash utility. It stands for "global regular expression print". Grep is used to match strings in files.</p>
<p>Here are some common uses of <code>grep</code>:</p>
<ol>
<li><p><strong>Search for a specific string in a file:</strong></p>
<pre><code class="lang-bash"> grep <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command searches for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search recursively in directories:</strong></p>
<pre><code class="lang-bash"> grep -r <span class="hljs-string">"search_string"</span> /path/to/directory
</code></pre>
<p> This command searches for "<code>search_string"</code> in all files within the specified directory and its subdirectories.</p>
</li>
<li><p><strong>Ignore case while searching:</strong></p>
<pre><code class="lang-bash"> grep -i <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command performs a case-insensitive search for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Display line numbers with matching lines:</strong></p>
<pre><code class="lang-bash"> grep -n <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command shows the line numbers along with the matching lines in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Count the number of matching lines:</strong></p>
<pre><code class="lang-bash"> grep -c <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command counts the number of lines that contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Invert match to display lines that do not match:</strong></p>
<pre><code class="lang-bash"> grep -v <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command displays all lines that do not contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search for a whole word:</strong></p>
<pre><code class="lang-bash"> grep -w <span class="hljs-string">"word"</span> filename
</code></pre>
<p> This command searches for the whole word "word" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Use extended regular expressions:</strong></p>
<pre><code class="lang-bash"> grep -E <span class="hljs-string">"pattern"</span> filename
</code></pre>
<p> This command allows the use of extended regular expressions for more complex pattern matching in the file named <code>filename</code>.</p>
</li>
</ol>
<p><strong>💡 Tip:</strong> If there are multiple files in a folder, you can use the below command to find the list of files containing the desired strings.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># find the list of files containing the desired strings</span>
grep -l <span class="hljs-string">"String to Match"</span> /path/to/directory
</code></pre>
<h4 id="heading-text-extraction-using-sed">Text extraction using <code>sed</code></h4>
<p><code>sed</code> stands for "stream editor". It processes data stream-wise, meaning it reads data one line at a time. <code>sed</code> allows you to search for patterns and perform actions on the lines that match those patterns.</p>
<p><strong>Basic syntax of</strong><code>sed</code>:</p>
<p>The basic syntax of <code>sed</code> is as follows:</p>
<pre><code class="lang-bash">sed [options] <span class="hljs-string">'command'</span> file_name
</code></pre>
<p>Here, <code>command</code> is used to perform operations like substitution, deletion, insertion, and so on, on the text data. The filename is the name of the file you want to process.</p>
<p><code>sed</code><strong>usage:</strong></p>
<p><strong>1. Substitution:</strong></p>
<p>The <code>s</code> flag is used to replace text. The <code>old-text</code> is replaced with <code>new-text</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/old-text/new-text/'</span> filename
</code></pre>
<p>For example, to change all instances of "error" to "warning" in the log file <code>system.log</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/error/warning/'</span> system.log
</code></pre>
<p><strong>2. Printing lines containing a specific pattern:</strong></p>
<p>Using <code>sed</code> to filter and display lines that match a specific pattern:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/pattern/p'</span> filename
</code></pre>
<p>For instance, to find all lines containing "ERROR":</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/ERROR/p'</span> system.log
</code></pre>
<p><strong>3. Deleting lines containing a specific pattern:</strong></p>
<p>You can delete lines from the output that match a specific pattern:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/pattern/d'</span> filename
</code></pre>
<p>For example, to remove all lines containing "DEBUG":</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/DEBUG/d'</span> system.log
</code></pre>
<p><strong>4. Extracting specific fields from a log line:</strong></p>
<p>You can use regular expressions to extract parts of lines. Suppose each log line starts with a date in the format "YYYY-MM-DD". You could extract just the date from each line:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'s/^\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\).*/\1/p'</span> system.log
</code></pre>
<h4 id="heading-text-parsing-with-awk">Text parsing with <code>awk</code></h4>
<p><code>awk</code> has the ability to easily split each line into fields. It's well-suited for processing structured text like log files.</p>
<p><strong>Basic syntax of</strong><code>awk</code></p>
<p>The basic syntax of <code>awk</code> is:</p>
<pre><code class="lang-bash">awk <span class="hljs-string">'pattern { action }'</span> file_name
</code></pre>
<p>Here, <code>pattern</code> is a condition that must be met for the <code>action</code> to be performed. If the pattern is omitted, the action is performed on every line.</p>
<p>In the coming examples, you'll use this log file as an example:</p>
<pre><code class="lang-bash">2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<ul>
<li><strong>Accessing columns using</strong><code>awk</code></li>
</ul>
<p>The fields in <code>awk</code> (separated by spaces by default) can be accessed using <code>$1</code>, <code>$2</code>, <code>$3</code>, and so on.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $1 }'</span> sample.log
<span class="hljs-comment"># output</span>
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25

zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $2 }'</span> sample.log
<span class="hljs-comment"># output</span>
09:00:00
09:01:00
09:02:00
09:03:00
09:04:00
09:05:00
09:06:00
09:07:00
09:08:00
09:09:00
</code></pre>
<ul>
<li><strong>Print lines containing a specific pattern (for example, ERROR)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'/ERROR/ { print $0 }'</span> logfile.log

<span class="hljs-comment"># output</span>
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
</code></pre>
<p>This prints all lines that contain "ERROR".</p>
<ul>
<li><strong>Extract the first field (Date and Time)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ print $1, $2 }'</span> logfile.log
<span class="hljs-comment"># output</span>
2024-04-25 09:00:00
2024-04-25 09:01:00
2024-04-25 09:02:00
2024-04-25 09:03:00
2024-04-25 09:04:00
2024-04-25 09:05:00
2024-04-25 09:06:00
2024-04-25 09:07:00
2024-04-25 09:08:007
2024-04-25 09:09:00
</code></pre>
<p>This will extract the first two fields from each line, which in this case would be the date and time.</p>
<ul>
<li><strong>Summarize occurrences of each log level</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ count[$3]++ } END { for (level in count) print level, count[level] }'</span> logfile.log

<span class="hljs-comment"># output</span>
 1
WARN 1
ERROR 1
DEBUG 2
INFO 6
</code></pre>
<p>The output will be a summary of the number of occurrences of each log level.</p>
<ul>
<li><strong>Filter out specific fields (for example, where the 3rd field is INFO)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ $3="INFO"; print }'</span> sample.log

<span class="hljs-comment"># output</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<p>This command will extract all lines where the 3rd field is "INFO".</p>
<p>💡 <strong>Tip:</strong> The default separator in <code>awk</code> is a space. If your log file uses a different separator, you can specify it using the <code>-F</code> option. For example, if your log file uses a colon as a separator, you can use <code>awk -F: '{ print $1 }' logfile.log</code> to extract the first field.</p>
<h4 id="heading-parsing-log-files-with-cut">Parsing log files with <code>cut</code></h4>
<p>The <code>cut</code> command is a simple yet powerful command used to extract sections of text from each line of input. As log files are structured and each field is delimited by a specific character, such as a space, tab, or a custom delimiter, <code>cut</code> does a very good job of extracting those specific fields.</p>
<p>The basic syntax of the cut command is:</p>
<pre><code class="lang-bash">cut [options] [file]
</code></pre>
<p>Some commonly used options for the cut command:</p>
<ul>
<li><p><code>-d</code> : Specifies a delimiter used as the field separator.</p>
</li>
<li><p><code>-f</code> : Selects the fields to be displayed.</p>
</li>
<li><p><code>-c</code> : Specifies character positions.</p>
</li>
</ul>
<p>For example, the command below would extract the first field (separated by a space) from each line of the log file:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1 logfile.log
</code></pre>
<p><strong>Examples of using</strong><code>cut</code><strong>for log parsing</strong></p>
<p>Assume you have a log file structured as follows, where fields are space-separated:</p>
<pre><code class="lang-bash">2024-04-25 08:23:01 INFO 192.168.1.10 User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 08:24:15 WARNING 192.168.1.10 Disk usage exceeds 90%.
2024-04-25 08:25:02 ERROR 10.0.0.5 Connection timed out.
...
</code></pre>
<p><code>cut</code> can be used in the following ways:</p>
<ol>
<li><strong>Extracting the time from each log entry</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 2 system.log

<span class="hljs-comment"># Output</span>
08:23:01
08:24:15
08:25:02
...
</code></pre>
<p>This command uses a space as a delimiter and selects the second field, which is the time component of each log entry.</p>
<ol start="2">
<li><strong>Extracting the IP addresses from the logs</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 4 system.log

<span class="hljs-comment"># Output</span>
192.168.1.10
192.168.1.10
10.0.0.5
</code></pre>
<p>This command extracts the fourth field, which is the IP address from each log entry.</p>
<ol start="3">
<li><strong>Extracting log levels (INFO, WARNING, ERROR)</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 3 system.log

<span class="hljs-comment"># Output</span>
INFO
WARNING
ERROR
</code></pre>
<p>This extracts the third field which contains the log level.</p>
<ol start="4">
<li><strong>Combining</strong><code>cut</code><strong>with other commands:</strong></li>
</ol>
<p>The output of other commands can be piped to the <code>cut</code> command. Let's say you want to filter logs before cutting. You can use <code>grep</code> to extract lines containing "ERROR" and then use <code>cut</code> to get specific information from those lines:</p>
<pre><code class="lang-bash">grep <span class="hljs-string">"ERROR"</span> system.log | cut -d <span class="hljs-string">' '</span> -f 1,2 

<span class="hljs-comment"># Output</span>
2024-04-25 08:25:02
</code></pre>
<p>This command first filters lines that include "ERROR", then extracts the date and time from these lines.</p>
<ol start="5">
<li><strong>Extracting multiple fields</strong>:</li>
</ol>
<p>It is possible to extract multiple fields at once by specifying a range or a comma-separated list of fields:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1,2,3 system.log` 

<span class="hljs-comment"># Output</span>
2024-04-25 08:23:01 INFO
2024-04-25 08:24:15 WARNING
2024-04-25 08:25:02 ERROR
...
</code></pre>
<p>The above command extracts the first three fields from each log entry that are date, time, and log level.</p>
<h4 id="heading-parsing-log-files-with-sort-and-uniq">Parsing log files with <code>sort</code> and <code>uniq</code></h4>
<p>Sorting and removing duplicates are common operations when working with log files. The <code>sort</code> and <code>uniq</code> commands are powerful commands used to sort and remove duplicates from the input, respectively.</p>
<p><strong>Basic syntax of sort</strong></p>
<p>The <code>sort</code> command organizes lines of text alphabetically or numerically.</p>
<pre><code class="lang-bash">sort [options] [file]
</code></pre>
<p>Some key options for the sort command:</p>
<ul>
<li><p><code>-n</code>: Sorts the file assuming the contents are numerical.</p>
</li>
<li><p><code>-r</code>: Reverses the order of sort.</p>
</li>
<li><p><code>-k</code>: Specifies a key or column number to sort on.</p>
</li>
<li><p><code>-u</code>: Sorts and removes duplicate lines.</p>
</li>
</ul>
<p>The <code>uniq</code> command is used to filter or count and report repeated lines in a file.</p>
<p>The syntax of <code>uniq</code> is:</p>
<pre><code class="lang-bash">uniq [options] [input_file] [output_file]
</code></pre>
<p>Some key options for the <code>uniq</code> command are:</p>
<ul>
<li><p><code>-c</code>: Prefixes lines by the number of occurrences.</p>
</li>
<li><p><code>-d</code>: Only prints duplicate lines.</p>
</li>
<li><p><code>-u</code>: Only prints unique lines.</p>
</li>
</ul>
<h4 id="heading-examples-of-using-sort-and-uniq-together-for-log-parsing">Examples of using <code>sort</code> and <code>uniq</code> together for log parsing</h4>
<p>Let's assume the following example log entries for these demonstrations:</p>
<pre><code class="lang-bash">2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-26 ERROR Connection timed out.
</code></pre>
<ol>
<li><strong>Sorting log entries by date</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This sorts the log entries alphabetically, which effectively sorts them by date if the date is the first field.</p>
<ol>
<li><strong>Sorting and removing duplicates</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command sorts the log file and pipes it to <code>uniq</code>, removing duplicate lines.</p>
<ol>
<li><strong>Counting occurrences of each line</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -c

<span class="hljs-comment"># Output</span>
2 2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
1 2024-04-25 WARNING Disk usage exceeds 90%.
2 2024-04-26 ERROR Connection timed out.
1 2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>Sorts the log entries and then counts each unique line. According to the output, the line <code>'2024-04-25 INFO User logged in successfully.'</code> appeared 2 times in the file.</p>
<ol>
<li><strong>Identifying unique log entries</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -u

<span class="hljs-comment"># Output</span>

2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command shows lines that are unique.</p>
<ol start="2">
<li><strong>Sorting by log level</strong>:</li>
</ol>
<pre><code class="lang-bash">sort -k2 system.log

<span class="hljs-comment"># Output</span>
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-25 WARNING Disk usage exceeds 90%.
</code></pre>
<p>Sorts the entries based on the second field, which is the log level.</p>
<h3 id="heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</h3>
<p>A process is a running instance of a program. A process consists of:</p>
<ul>
<li><p>An address space of the allocated memory.</p>
</li>
<li><p>Process states.</p>
</li>
<li><p>Properties such as ownership, security attributes, and resource usage.</p>
</li>
</ul>
<p>A process also has an environment that consists of:</p>
<ul>
<li><p>Local and global variables</p>
</li>
<li><p>The current scheduling context</p>
</li>
<li><p>Allocated system resources, such as network ports or file descriptors.</p>
</li>
</ul>
<p>When you run the <code>ls -l</code> command, the operating system creates a new process to execute the command. The process has an ID, a state, and runs until the command completes.</p>
<h4 id="heading-understanding-process-creation-and-lifecycle">Understanding process creation and lifecycle</h4>
<p>In Ubuntu, all processes originate from the initial system process called <code>systemd</code>, which is the first process started by the kernel during boot.</p>
<p>The <code>systemd</code> process has a process ID (PID) of <code>1</code> and is responsible for initializing the system, starting and managing other processes, and handling system services. All other processes on the system are descendants of <code>systemd</code>.</p>
<p>A parent process duplicates its own address space (fork) to create a new (child) process structure. Each new process is assigned a unique process ID (PID) for tracking and security purposes. The PID and the parent's process ID (PPID) are part of the new process environment. Any process can create a child process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584071059/f24fac4b-18f3-4a39-8659-93d32c533256.png" alt="Process and its initialization to parent and child" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Through the fork routine, a child process inherits security identities, previous and current file descriptors, port and resource privileges, environment variables, and program code. A child process may then execute its own program code.</p>
<p>Typically, a parent process sleeps while the child process runs, setting a request (wait) to be notified when the child completes.</p>
<p>Upon exiting, the child process has already closed or discarded its resources and environment. The only remaining resource, known as a zombie, is an entry in the process table. The parent, signaled awake when the child exits, cleans the process table of the child's entry, thus freeing the last resource of the child process. The parent process then continues executing its own program code.</p>
<h4 id="heading-understanding-process-states">Understanding process states</h4>
<p>Processes in Linux assume different states during their lifecycle. The state of a process indicates what the process is currently doing and how it is interacting with the system. The processes transition between states based on their execution status and the system's scheduling algorithm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584116150/3054dfe2-c42c-4d62-9e12-e3aec479d53a.png" alt="Linux process states and transitions" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The processes in a Linux system can be in one of the following states:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>(new)</strong></td><td>Initial state when a process is created via a fork system call.</td></tr>
<tr>
<td><strong>Runnable (ready) (R)</strong></td><td>Process is ready to run and waiting to be scheduled on a CPU.</td></tr>
<tr>
<td><strong>Running (user) (R)</strong></td><td>Process is executing in user mode, running user applications.</td></tr>
<tr>
<td><strong>Running (kernel) (R)</strong></td><td>Process is executing in kernel mode, handling system calls or hardware interrupts.</td></tr>
<tr>
<td><strong>Sleeping (S)</strong></td><td>Process is waiting for an event (for example, I/O operation) to complete and can be easily awakened.</td></tr>
<tr>
<td><strong>Sleeping (uninterruptible) (D)</strong></td><td>Process is in an uninterruptible sleep state, waiting for a specific condition (usually I/O) to complete, and cannot be interrupted by signals.</td></tr>
<tr>
<td><strong>Sleeping (disk sleep) (K)</strong></td><td>Process is waiting for disk I/O operations to complete.</td></tr>
<tr>
<td><strong>Sleeping (idle) (I)</strong></td><td>Process is idle, not doing any work, and waiting for an event to occur.</td></tr>
<tr>
<td><strong>Stopped (T)</strong></td><td>Process execution has been stopped, typically by a signal, and can be resumed later.</td></tr>
<tr>
<td><strong>Zombie (Z)</strong></td><td>Process has completed execution but still has an entry in the process table, waiting for its parent to read its exit status.</td></tr>
</tbody>
</table>
</div><p>The processes transition between these states in the following ways:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Transition</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Fork</strong></td><td>Creates a new process from a parent process, transitioning from (new) to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Schedule</strong></td><td>Scheduler selects a runnable process, transitioning it to Running (user) or Running (kernel) state.</td></tr>
<tr>
<td><strong>Run</strong></td><td>Process transitions from Runnable (ready) (R) to Running (kernel) (R) when scheduled for execution.</td></tr>
<tr>
<td><strong>Preempt or Reschedule</strong></td><td>Process can be preempted or rescheduled, moving it back to Runnable (ready) (R) state.</td></tr>
<tr>
<td><strong>Syscall</strong></td><td>Process makes a system call, transitioning from Running (user) (R) to Running (kernel) (R).</td></tr>
<tr>
<td><strong>Return</strong></td><td>Process completes a system call and returns to Running (user) (R).</td></tr>
<tr>
<td><strong>Wait</strong></td><td>Process waits for an event, transitioning from Running (kernel) (R) to one of the Sleeping states (S, D, K, or I).</td></tr>
<tr>
<td><strong>Event or Signal</strong></td><td>Process is awakened by an event or signal, moving it from a Sleeping state back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Suspend</strong></td><td>Process is suspended, transitioning from Running (kernel) or Runnable (ready) to Stopped (T).</td></tr>
<tr>
<td><strong>Resume</strong></td><td>Process is resumed, moving from Stopped (T) back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Exit</strong></td><td>Process terminates, transitioning from Running (user) or Running (kernel) to Zombie (Z).</td></tr>
<tr>
<td><strong>Reap</strong></td><td>Parent process reads the exit status of the zombie process, removing it from the process table.</td></tr>
</tbody>
</table>
</div><h4 id="heading-how-to-view-processes">How to view processes</h4>
<p>You can use the <code>ps</code> command along with a combination of options to view processes on a Linux system. The <code>ps</code> command is used to display information about a selection of active processes. For example, <code>ps aux</code> displays all processes running on the system.</p>
<pre><code class="lang-bash">zaira@zaira:~$ ps aux
<span class="hljs-comment"># Output</span>
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0 168140 11352 ?        Ss   May21   0:18 /sbin/init splash
root           2  0.0  0.0      0     0 ?        S    May21   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_par_gp]
root           5  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [slub_flushwq]
root           6  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [netns]
root          11  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [mm_percpu_wq]
root          12  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_kthread]
root          13  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_rude_kthread]
*... output truncated ....*
</code></pre>
<p>The output above shows a snapshot of the currently running processes on the system. Each row represents a process with the following columns:</p>
<ol>
<li><p><code>USER</code>: The user who owns the process.</p>
</li>
<li><p><code>PID</code>: The process ID.</p>
</li>
<li><p><code>%CPU</code>: The CPU usage of the process.</p>
</li>
<li><p><code>%MEM</code>: The memory usage of the process.</p>
</li>
<li><p><code>VSZ</code>: The virtual memory size of the process.</p>
</li>
<li><p><code>RSS</code>: The resident set size, that is the non-swapped physical memory that a task has used.</p>
</li>
<li><p><code>TTY</code>: The controlling terminal of the process. A <code>?</code> indicates no controlling terminal.</p>
</li>
<li><p><code>STAT</code>: The process state.</p>
<ul>
<li><p><code>R</code>: Running</p>
</li>
<li><p><code>I</code> or <code>S</code>: Interruptible sleep (waiting for an event to complete)</p>
</li>
<li><p><code>D</code>: Uninterruptible sleep (usually IO)</p>
</li>
<li><p><code>T</code>: Stopped (either by a job control signal or because it is being traced)</p>
</li>
<li><p><code>Z</code>: Zombie (terminated but not reaped by its parent)</p>
</li>
<li><p><code>Ss</code>: Session leader. This is a process that has started a session, and it is a leader of a group of processes and can control terminal signals. The first <code>S</code> indicates the sleeping state, and the second <code>s</code> indicates it is a session leader.</p>
</li>
</ul>
</li>
<li><p><code>START</code>: The starting time or date of the process.</p>
</li>
<li><p><code>TIME</code>: The cumulative CPU time.</p>
</li>
<li><p><code>COMMAND</code>: The command that started the process.</p>
</li>
</ol>
<h4 id="heading-background-and-foreground-processes">Background and foreground processes</h4>
<p>In this section, you'll learn how you can control jobs by running them in the background or foreground.</p>
<p>A job is a process that is started by a shell. When you run a command in the terminal, it is considered a job. A job can run in the foreground or the background.</p>
<p>To demonstrate control, you'll first create 3 processes and then run them in the background. After that, you'll list the processes and alternate them between the foreground and background. You'll see how to put them to sleep or exit completely.</p>
<ol>
<li>Create Three Processes</li>
</ol>
<p>Open a terminal and start three long-running processes. Use the <code>sleep</code> command, that keeps the process running for a specified number of seconds.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># run sleep command for 300, 400, and 500 seconds</span>
sleep 300 &amp;
sleep 400 &amp;
sleep 500 &amp;
</code></pre>
<p>The <code>&amp;</code> at the end of each command moves the process to the background.</p>
<ol start="2">
<li>Display Background Jobs</li>
</ol>
<p>Use the <code>jobs</code> command to display the list of background jobs.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
</code></pre>
<p>The output should look something like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<ol start="3">
<li>Bring a Background Job to the Foreground</li>
</ol>
<p>To bring a background job to the foreground, use the <code>fg</code> command followed by the job number. For example, to bring the first job (<code>sleep 300</code>) to the foreground:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">fg</span> %1
</code></pre>
<p>This will bring job <code>1</code> to the foreground.</p>
<ol start="4">
<li>Move the Foreground Job Back to the Background</li>
</ol>
<p>While the job is running in the foreground, you can suspend it and move it back to the background by pressing <code>Ctrl+Z</code> to suspend the job.</p>
<p>A suspended job will look like this:</p>
<pre><code class="lang-bash">zaira@zaira:~$ <span class="hljs-built_in">fg</span> %1
sleep 300

^Z
[1]+  Stopped                 sleep 300

zaira@zaira:~$ <span class="hljs-built_in">jobs</span>
<span class="hljs-comment"># suspended job </span>
[1]+  Stopped                 sleep 300
[2]   Running                 sleep 400 &amp;
[3]-  Running                 sleep 500 &amp;
</code></pre>
<p>Now use the <code>bg</code> command to resume the job with ID 1 in the background.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Press Ctrl+Z to suspend the foreground job</span>
<span class="hljs-comment"># Then, resume it in the background</span>
<span class="hljs-built_in">bg</span> %1
</code></pre>
<ol start="5">
<li>Display the jobs again</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<p>In this exercise, you:</p>
<ul>
<li><p>Started three background processes using sleep commands.</p>
</li>
<li><p>Used jobs to display the list of background jobs.</p>
</li>
<li><p>Brought a job to the foreground with <code>fg %job_number</code>.</p>
</li>
<li><p>Suspended the job with <code>Ctrl+Z</code> and moved it back to the background with <code>bg %job_number</code>.</p>
</li>
<li><p>Used jobs again to verify the status of the background jobs.</p>
</li>
</ul>
<p>Now you know how to control jobs.</p>
<h4 id="heading-killing-processes">Killing processes</h4>
<p>It is possible to terminate an unresponsive or unwanted process using the <code>kill</code> command. The <code>kill</code> command sends a signal to a process ID, asking it to terminate.</p>
<p>A number of options are available with the <code>kill</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Options available with kill</span>

<span class="hljs-built_in">kill</span> -l
 1) SIGHUP     2) SIGINT     3) SIGQUIT     4) SIGILL     5) SIGTRAP
 6) SIGABRT     7) SIGBUS     8) SIGFPE     9) SIGKILL    10) SIGUSR1
11) SIGSEGV    12) SIGUSR2    13) SIGPIPE    14) SIGALRM    15) SIGTERM
16) SIGSTKFLT    17) SIGCHLD    18) SIGCONT    19) SIGSTOP    20) SIGTSTP
21) SIGTTIN    22) SIGTTOU    23) SIGURG    24) 
...terminated
</code></pre>
<p>Here are some examples of the <code>kill</code> command in Linux:</p>
<ol>
<li><p><strong>Kill a process by PID (Process ID):</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> 1234
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to the process with PID 1234, requesting it to terminate.</p>
</li>
<li><p><strong>Kill a process by name:</strong></p>
<pre><code class="lang-bash"> pkill process_name
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes with the specified name.</p>
</li>
<li><p><strong>Forcefully kill a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -9 1234
</code></pre>
<p> This command sends the <code>SIGKILL</code> signal to the process with PID 1234, forcefully terminating it.</p>
</li>
<li><p><strong>Send a specific signal to a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -s SIGSTOP 1234
</code></pre>
<p> This command sends the <code>SIGSTOP</code> signal to the process with PID 1234, stopping it.</p>
</li>
<li><p><strong>Kill all processes owned by a specific user:</strong></p>
<pre><code class="lang-bash"> pkill -u username
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes owned by the specified user.</p>
</li>
</ol>
<p>These examples demonstrate various ways to use the <code>kill</code> command to manage processes in a Linux environment.</p>
<p>Here is the information about the <code>kill</code> command options and signals in a tabular form: This table summarizes the most common <code>kill</code> command options and signals used in Linux for managing processes.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command / Option</td><td>Signal</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>kill &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Requests the process to terminate gracefully (default signal).</td></tr>
<tr>
<td><code>kill -9 &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -SIGKILL &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -15 &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -SIGTERM &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -1 &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -SIGHUP &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -2 &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -SIGINT &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -3 &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -SIGQUIT &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -19 &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -SIGSTOP &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -18 &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>kill -SIGCONT &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>killall &lt;name&gt;</code></td><td>Varies</td><td>Sends a signal to all processes with the given name.</td></tr>
<tr>
<td><code>killall -9 &lt;name&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes with the given name.</td></tr>
<tr>
<td><code>pkill &lt;pattern&gt;</code></td><td>Varies</td><td>Sends a signal to processes based on a pattern match.</td></tr>
<tr>
<td><code>pkill -9 &lt;pattern&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes matching the pattern.</td></tr>
<tr>
<td><code>xkill</code></td><td><code>SIGKILL</code></td><td>Graphical utility that allows clicking on a window to kill the corresponding process.</td></tr>
</tbody>
</table>
</div><h3 id="heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</h3>
<p>Reading an input and writing an output is an essential part of understanding the command line and shell scripting. In Linux, every process has three default streams:</p>
<ol>
<li><p>Standard Input (<code>stdin</code>): This stream is used for input, typically from the keyboard. When a program reads from <code>stdin</code>, it receives data entered by the user or redirected from a file. A file descriptor is a unique identifier that the operating system assigns to an open file in order to keep track of open files.</p>
<p> The file descriptor for <code>stdin</code> is <code>0</code>.</p>
</li>
<li><p>Standard Output (<code>stdout</code>): This is the default output stream where a process writes its output. By default, the standard output is the terminal. The output can also be redirected to a file or another program. The file descriptor for <code>stdout</code> is <code>1</code>.</p>
</li>
<li><p>Standard Error (<code>stderr</code>): This is the default error stream where a process writes its error messages. By default, the standard error is the terminal, allowing error messages to be seen even if <code>stdout</code> is redirected. The file descriptor for <code>stderr</code> is <code>2</code>.</p>
</li>
</ol>
<h4 id="heading-redirection-and-pipelines">Redirection and Pipelines</h4>
<p><strong>Redirection:</strong> You can redirect the error and output streams to files or other commands. For example:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirecting stdout to a file</span>
ls &gt; output.txt

<span class="hljs-comment"># Redirecting stderr to a file</span>
ls non_existent_directory 2&gt; error.txt

<span class="hljs-comment"># Redirecting both stdout and stderr to a file</span>
ls non_existent_directory &gt; all_output.txt 2&gt;&amp;1
</code></pre>
<p>In the last command,</p>
<ul>
<li><p><code>ls non_existent_directory</code>: lists the contents of a directory named non_existent_directory. Since this directory does not exist, <code>ls</code> will generate an error message.</p>
</li>
<li><p><code>&gt; all_output.txt</code>: The <code>&gt;</code> operator redirects the standard output (<code>stdout</code>) of the <code>ls</code> command to the file <code>all_output.txt</code>. If the file does not exist, it will be created. If it does exist, its contents will be overwritten.</p>
</li>
<li><p><code>2&gt;&amp;1:</code>: Here, <code>2</code> represents the file descriptor for standard error (<code>stderr</code>). <code>&amp;1</code> represents the file descriptor for standard output (<code>stdout</code>). The <code>&amp;</code> character is used to specify that <code>1</code> is not the file name but a file descriptor.</p>
</li>
</ul>
<p>So, <code>2&gt;&amp;1</code> means "redirect stderr (2) to wherever stdout (1) is currently going," which in this case is the file <code>all_output.txt</code>. Therefore, both the output (if there were any) and the error message from <code>ls</code> will be written to <code>all_output.txt</code>.</p>
<p><strong>Pipelines:</strong></p>
<p>You can use pipes (<code>|</code>) to pass the output of one command as the input to another:</p>
<pre><code class="lang-bash">ls | grep image
<span class="hljs-comment"># Output</span>
image-10.png
image-11.png
image-12.png
image-13.png
... Output truncated ...
</code></pre>
<h3 id="heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</h3>
<p>Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or other specific time basis. The automation capabilities provided by cron play a crucial role in Linux system administration.</p>
<p>The <code>crond</code> daemon (a type of computer program that runs in the background) enables cron functionality. The cron reads the <strong>crontab</strong> (cron tables) for running predefined scripts.</p>
<p>By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.</p>
<p><strong>What are cron jobs in Linux?</strong></p>
<p>Any task that you schedule through crons is called a cron job.</p>
<p>Now, let's see how cron jobs work.</p>
<h4 id="heading-how-to-control-access-to-crons">How to control access to crons</h4>
<p>In order to use cron jobs, an admin needs to allow cron jobs to be added for users in the <code>/etc/cron.allow</code> file.</p>
<p>If you get a prompt like this, it means you don't have permission to use cron.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-51.png" alt="Cron job addition denied for user John." width="600" height="400" loading="lazy"></p>
<p>To allow John to use crons, include his name in <code>/etc/cron.allow</code>. Create the file if it doesn't exist. This will allow John to create and edit cron jobs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-52.png" alt="Allowing John in file cron.allow" width="600" height="400" loading="lazy"></p>
<p>Users can also be denied access to cron job access by entering their usernames in the file <code>/etc/cron.d/cron.deny</code>.</p>
<h4 id="heading-how-to-add-cron-jobs-in-linux">How to add cron jobs in Linux</h4>
<p>First, to use cron jobs, you'll need to check the status of the cron service. If cron is not installed, you can easily download it through the package manager. Just use this to check:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Check cron service on Linux system</span>
sudo systemctl status cron.service
</code></pre>
<h4 id="heading-cron-job-syntax">Cron job syntax</h4>
<p>Crontabs use the following flags for adding and listing cron jobs:</p>
<ul>
<li><p><code>crontab -e</code>: edits crontab entries to add, delete, or edit cron jobs.</p>
</li>
<li><p><code>crontab -l</code>: list all the cron jobs for the current user.</p>
</li>
<li><p><code>crontab -u username -l</code>: list another user's crons.</p>
</li>
<li><p><code>crontab -u username -e</code>: edit another user's crons.</p>
</li>
</ul>
<p>When you list crons and they exist, you'll see something like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Cron job example</span>
* * * * * sh /path/to/script.sh
</code></pre>
<p>In the above example,</p>
<ul>
<li><code>*</code> represents minute(s) hour(s) day(s) month(s) weekday(s), respectively. See details of these values below:</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td><strong>VALUE</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Minutes</td><td>0-59</td><td>Command will be executed at the specific minute.</td></tr>
<tr>
<td>Hours</td><td>0-23</td><td>Command will be executed at the specific hour.</td></tr>
<tr>
<td>Days</td><td>1-31</td><td>Commands will be executed in these days of the months.</td></tr>
<tr>
<td>Months</td><td>1-12</td><td>The month in which tasks need to be executed.</td></tr>
<tr>
<td>Weekdays</td><td>0-6</td><td>Days of the week where commands will run. Here, 0 is Sunday.</td></tr>
</tbody>
</table>
</div><ul>
<li><p><code>sh</code> represents that the script is a bash script and should be run from <code>/bin/bash</code>.</p>
</li>
<li><p><code>/path/to/script.sh</code> specifies the path to the script.</p>
</li>
</ul>
<p>Below is a summary of the cron job syntax:</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">*</span>   <span class="hljs-emphasis">*   *</span>   <span class="hljs-emphasis">*   *</span>  sh /path/to/script/script.sh
|   |   |   |   |              |
|   |   |   |   |      Command or Script to Execute        
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |
|   |   |   | Day of the Week(0-6)
|   |   |   |
|   |   | Month of the Year(1-12)
|   |   |
|   | Day of the Month(1-31)  
|   |
| Hour(0-23)  
|
Min(0-59)
</code></pre>
<h4 id="heading-cron-job-examples">Cron job examples</h4>
<p>Below are some examples of scheduling cron jobs.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>SCHEDULE</strong></td><td><strong>SCHEDULED VALUE</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>5 0 * 8 *</code></td><td>At 00:05 in August.</td></tr>
<tr>
<td><code>5 4 * * 6</code></td><td>At 04:05 on Saturday.</td></tr>
<tr>
<td><code>0 22 * * 1-5</code></td><td>At 22:00 on every day-of-week from Monday through Friday.</td></tr>
</tbody>
</table>
</div><p>It's okay if you are unable to grasp this all at once. You can practice and generate cron schedules with the <a target="_blank" href="https://crontab.guru/">crontab guru</a> website.</p>
<h4 id="heading-how-to-set-up-a-cron-job">How to set up a cron job</h4>
<p>In this section, we will look at an example of how to schedule a simple script with a cron job.</p>
<ol>
<li>Create a script called <code>date-script.sh</code> which prints the system date and time and appends it to a file. The script is shown below:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">echo</span> `date` &gt;&gt; date-out.txt
</code></pre>
<p>2.  Make the script executable by giving it execution rights.</p>
<pre><code class="lang-bash">chmod 775 date-script.sh
</code></pre>
<p>3.  Add the script in the crontab using <code>crontab -e</code>.</p>
<p>Here, we have scheduled it to run per minute.</p>
<pre><code class="lang-bash">*/1 * * * * /bin/sh /root/date-script.sh
</code></pre>
<p>4.  Check the output of the file <code>date-out.txt</code>. According to the script, the system date should be printed to this file every minute.</p>
<pre><code class="lang-bash">cat date-out.txt
<span class="hljs-comment"># output</span>
Wed 26 Jun 16:59:33 PKT 2024
Wed 26 Jun 17:00:01 PKT 2024
Wed 26 Jun 17:01:01 PKT 2024
Wed 26 Jun 17:02:01 PKT 2024
Wed 26 Jun 17:03:01 PKT 2024
Wed 26 Jun 17:04:01 PKT 2024
Wed 26 Jun 17:05:01 PKT 2024
Wed 26 Jun 17:06:01 PKT 2024
Wed 26 Jun 17:07:01 PKT 2024
</code></pre>
<p><strong>How to troubleshoot crons</strong></p>
<p>Crons are really helpful, but they might not always work as intended. Fortunately, there are some effective methods you can use to troubleshoot them.</p>
<p><strong>1. Check the schedule.</strong></p>
<p>First, you can try verifying the schedule that's set for the cron. You can do that with the syntax you saw in the above sections.</p>
<p><strong>2</strong>. <strong>Check cron logs.</strong></p>
<p>First, you need to check if the cron has run at the intended time or not. In Ubuntu, you can verify this from the cron logs located at <code>/var/log/syslog</code>.</p>
<p>If there is an entry in these logs at the correct time, it means the cron has run according to the schedule you set.</p>
<p>Below are the logs of our cron job example. Note the first column which shows the timestamp. The path of the script is also mentioned at the end of the line. Line #1, 3, and 5 show that the script ran as intended.</p>
<pre><code class="lang-bash">1 Jun 26 17:02:01 zaira-ThinkPad CRON[27834]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
2 Jun 26 17:02:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
3 Jun 26 17:03:01 zaira-ThinkPad CRON[28255]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
4 Jun 26 17:03:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
5 Jun 26 17:04:01 zaira-ThinkPad CRON[28538]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
</code></pre>
<p><strong>3. Redirect cron output to a file.</strong></p>
<p>You can redirect a cron's output to a file and check the file for any possible errors.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirect cron output to a file</span>
* * * * * sh /path/to/script.sh &amp;&gt; log_file.log
</code></pre>
<h3 id="heading-87-linux-networking-basics">8.7. Linux Networking Basics</h3>
<p>Linux offers a number of commands to view network related information. In this section we will briefly discuss some of the commands.</p>
<h4 id="heading-view-network-interfaces-with-ifconfig">View network interfaces with <code>ifconfig</code></h4>
<p>The <code>ifconfig</code> command gives information about network interfaces. Here is an example output:</p>
<pre><code class="lang-bash">ifconfig

<span class="hljs-comment"># Output</span>
eth0: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt;  mtu 1500
        inet 192.168.1.100  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::a00:27ff:fe4e:66a1  prefixlen 64  scopeid 0x20&lt;link&gt;
        ether 08:00:27:4e:66:a1  txqueuelen 1000  (Ethernet)
        RX packets 1024  bytes 654321 (654.3 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 512  bytes 123456 (123.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73&lt;UP,LOOPBACK,RUNNING&gt;  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10&lt;host&gt;
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 256  bytes 20480 (20.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 256  bytes 20480 (20.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code></pre>
<p>The output of the <code>ifconfig</code> command shows the network interfaces configured on the system, along with details such as IP addresses, MAC addresses, packet statistics, and more.</p>
<p>These interfaces can be physical or virtual devices.</p>
<p>To extract IPv4 and IPv6 addresses, you can use <code>ip -4 addr</code> and <code>ip -6 addr</code>, respectively.</p>
<p><strong>View network activity with</strong><code>netstat</code></p>
<p>The <code>netstat</code> command shows network activity and stats by giving the following information:</p>
<p>Here are some examples of using the <code>netstat</code> command in the command line:</p>
<ol>
<li><p><strong>Display all listening and non-listening sockets:</strong></p>
<pre><code class="lang-bash"> netstat -a
</code></pre>
</li>
<li><p><strong>Show only listening ports:</strong></p>
<pre><code class="lang-bash"> netstat -l
</code></pre>
</li>
<li><p><strong>Display network statistics:</strong></p>
<pre><code class="lang-bash"> netstat -s
</code></pre>
</li>
<li><p><strong>Show routing table:</strong></p>
<pre><code class="lang-bash"> netstat -r
</code></pre>
</li>
<li><p><strong>Display TCP connections:</strong></p>
<pre><code class="lang-bash"> netstat -t
</code></pre>
</li>
<li><p><strong>Display UDP connections:</strong></p>
<pre><code class="lang-bash"> netstat -u
</code></pre>
</li>
<li><p><strong>Show network interfaces:</strong></p>
<pre><code class="lang-bash"> netstat -i
</code></pre>
</li>
<li><p><strong>Display PID and program names for connections:</strong></p>
<pre><code class="lang-bash"> netstat -p
</code></pre>
</li>
<li><p><strong>Show statistics for a specific protocol (for example, TCP):</strong></p>
<pre><code class="lang-bash"> netstat -st
</code></pre>
</li>
<li><p><strong>Display extended information:</strong></p>
<pre><code class="lang-bash">netstat -e
</code></pre>
</li>
</ol>
<h4 id="heading-check-network-connectivity-between-two-devices-using-ping">Check network connectivity between two devices using <code>ping</code></h4>
<p><code>ping</code> is used to test network connectivity between two devices. It sends ICMP packets to the target device and waits for a response.</p>
<pre><code class="lang-bash">ping google.com
</code></pre>
<p><code>ping</code> tests if you get a response back without getting a timeout.</p>
<pre><code class="lang-bash">ping google.com
PING google.com (142.250.181.46) 56(84) bytes of data.
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=1 ttl=60 time=78.3 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=2 ttl=60 time=141 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=3 ttl=60 time=205 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=4 ttl=60 time=100 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 78.308/131.053/204.783/48.152 ms
</code></pre>
<p>You can stop the response with <code>Ctrl + C</code>.</p>
<h4 id="heading-testing-endpoints-with-the-curl-command">Testing endpoints with the <code>curl</code> command</h4>
<p>The <code>curl</code> command stands for "client URL". It is used to transfer data to or from a server. It can also be used to test API endpoints that helps in troubleshooting system and application errors.</p>
<p>As an example, you can use <a target="_blank" href="http://www.official-joke-api.appspot.com/"><code>http://www.official-joke-api.appspot.com/</code></a> to experiment with the <code>curl</code> command.</p>
<ul>
<li>The <code>curl</code> command without any options uses the GET method by default.</li>
</ul>
<pre><code class="lang-bash">curl http://www.official-joke-api.appspot.com/random_joke
{<span class="hljs-string">"type"</span>:<span class="hljs-string">"general"</span>,
<span class="hljs-string">"setup"</span>:<span class="hljs-string">"What did the fish say when it hit the wall?"</span>,<span class="hljs-string">"punchline"</span>:<span class="hljs-string">"Dam."</span>,<span class="hljs-string">"id"</span>:1}
</code></pre>
<ul>
<li><code>curl -o</code> saves the output to the mentioned file.</li>
</ul>
<pre><code class="lang-bash">curl -o random_joke.json http://www.official-joke-api.appspot.com/random_joke
<span class="hljs-comment"># saves the output to random_joke.json</span>
</code></pre>
<ul>
<li><code>curl -I</code> fetches only the headers.</li>
</ul>
<pre><code class="lang-bash">curl -I http://www.official-joke-api.appspot.com/random_joke
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Vary: Accept-Encoding
X-Powered-By: Express
Access-Control-Allow-Origin: *
ETag: W/<span class="hljs-string">"71-NaOSpKuq8ChoxdHD24M0lrA+JXA"</span>
X-Cloud-Trace-Context: 2653a86b36b8b131df37716f8b2dd44f
Content-Length: 113
Date: Thu, 06 Jun 2024 10:11:50 GMT
Server: Google Frontend
</code></pre>
<h3 id="heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</h3>
<h4 id="heading-system-activity-report-with-sar">System activity report with <code>sar</code></h4>
<p>The <code>sar</code> command in Linux is a powerful tool for collecting, reporting, and saving system activity information. It's part of the <code>sysstat</code> package and is widely used for monitoring system performance over time.</p>
<p>To use <code>sar</code> you first need to install <code>syssstat</code> using <code>sudo apt install sysstat</code>.</p>
<p>Once installed, start the service with <code>sudo systemctl start sysstat</code>.</p>
<p>Verify the status with <code>sudo systemctl status sysstat</code>.</p>
<p>Once the status is active, the system will start collecting various stats that you can use to access and analyze historical data. We'll see that in detail soon.</p>
<p>The syntax of the <code>sar</code> command is as follows:</p>
<pre><code class="lang-bash">sar [options] [interval] [count]
</code></pre>
<p>For example, <code>sar -u 1 3</code> will display CPU utilization statistics every second for three times.</p>
<pre><code class="lang-bash">sar -u 1 3
<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:09:26        CPU     %user     %nice   %system   %iowait    %steal     %idle
19:09:27        all      3.78      0.00      2.18      0.08      0.00     93.96
19:09:28        all      4.02      0.00      2.01      0.08      0.00     93.89
19:09:29        all      6.89      0.00      2.10      0.00      0.00     91.01
Average:        all      4.89      0.00      2.10      0.06      0.00     92.95
</code></pre>
<p>Here are some common use cases and examples of how to use the <code>sar</code> command.</p>
<p><code>sar</code> can be used for a variety of purposes:</p>
<h5 id="heading-1-memory-usage">1. Memory usage</h5>
<p>To check memory usage (free and used), use:</p>
<pre><code class="lang-bash">sar -r 1 3

Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:10:46    kbmemfree   kbavail kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact   kbdirty
19:10:47      4600104   8934352   5502124     36.32    375844   4158352  15532012     65.99   6830564   2481260       264
19:10:48      4644668   8978940   5450252     35.98    375852   4165648  15549184     66.06   6776388   2481284        36
19:10:49      4646548   8980860   5448328     35.97    375860   4165648  15549224     66.06   6774368   2481292       116
Average:      4630440   8964717   5466901     36.09    375852   4163216  15543473     66.04   6793773   2481279       139
</code></pre>
<p>This command displays memory statistics every second three times.</p>
<h5 id="heading-2-swap-space-utilization">2. Swap space utilization</h5>
<p>To view swap space utilization statistics, use:</p>
<pre><code class="lang-bash">sar -S 1 3

sar -S 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:11:20    kbswpfree kbswpused  %swpused  kbswpcad   %swpcad
19:11:21      8388604         0      0.00         0      0.00
19:11:22      8388604         0      0.00         0      0.00
19:11:23      8388604         0      0.00         0      0.00
Average:      8388604         0      0.00         0      0.00
</code></pre>
<p>This command helps monitor the swap usage, which is crucial for systems running out of physical memory.</p>
<h5 id="heading-3-io-devices-load">3. I/O devices load</h5>
<p>To report activity for block devices and block device partitions:</p>
<pre><code class="lang-bash">sar -d 1 3
</code></pre>
<p>This command provides detailed stats about data transfers to and from block devices, and is useful for diagnosing I/O bottlenecks.</p>
<h5 id="heading-5-network-statistics">5. Network statistics</h5>
<p>To view network statistics, like number of packets received (transmitted) by the network interface:</p>
<pre><code class="lang-bash">sar -n DEV 1 3
<span class="hljs-comment"># -n DEV tells sar to report network device interfaces</span>
sar -n DEV 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:12:47        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
19:12:48           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       wlp3s0     10.00      3.00      1.83      0.37      0.00      0.00      0.00      0.00
19:12:48    br-5129d04f972f      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
.
.
.

Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
Average:           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Average:       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
...output truncated...
</code></pre>
<p>This displays network statistics every second for three seconds, helping in monitoring network traffic.</p>
<h5 id="heading-6-historical-data">6. Historical data</h5>
<p>Recall that previously we installed the <code>sysstat</code> package and ran the service. Follow the steps below to enable and access historical data.</p>
<ol>
<li><p><strong>Enable data collection:</strong> Edit the <code>sysstat</code> configuration file to enable data collection.</p>
<pre><code class="lang-bash"> sudo nano /etc/default/sysstat
</code></pre>
<p> Change <code>ENABLED="false"</code> to <code>ENABLED="true"</code>.</p>
<pre><code class="lang-bash"> vim /etc/default/sysstat
 <span class="hljs-comment">#</span>
 <span class="hljs-comment"># Default settings for /etc/init.d/sysstat, /etc/cron.d/sysstat</span>
 <span class="hljs-comment"># and /etc/cron.daily/sysstat files</span>
 <span class="hljs-comment">#</span>

 <span class="hljs-comment"># Should sadc collect system activity informations? Valid values</span>
 <span class="hljs-comment"># are "true" and "false". Please do not put other values, they</span>
 <span class="hljs-comment"># will be overwritten by debconf!</span>
 ENABLED=<span class="hljs-string">"true"</span>
</code></pre>
</li>
<li><p><strong>Configure data collection interval:</strong> Edit the cron job configuration to set the data collection interval.</p>
<pre><code class="lang-bash"> sudo nano /etc/cron.d/sysstat
</code></pre>
<p> By default, it collects data every 10 minutes. You can adjust the interval by modifying the cron job schedule. The relevant files will go to the <code>/var/log/sysstat</code> folder.</p>
</li>
<li><p><strong>View historical data:</strong> Use the <code>sar</code> command to view historical data. For example, to view CPU usage for the current day:</p>
<pre><code class="lang-bash"> sar -u
</code></pre>
<p> To view data from a specific date:</p>
<pre><code class="lang-bash"> sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa&lt;DD&gt;
</code></pre>
<p> Replace <code>&lt;DD&gt;</code> with the day of the month for which you want to view the data.</p>
<p> In the below command, <code>/var/log/sysstat/sa04</code> gives stats for the 4th day of the current month.</p>
</li>
</ol>
<pre><code class="lang-bash">sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa04
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

15:20:49     LINUX RESTART    (12 CPU)

16:13:30     LINUX RESTART    (12 CPU)

18:16:00        CPU     %user     %nice   %system   %iowait    %steal     %idle
18:16:01        all      0.25      0.00      0.67      0.08      0.00     99.00
Average:        all      0.25      0.00      0.67      0.08      0.00     99.00
</code></pre>
<h5 id="heading-7-real-time-cpu-interruptions">7. Real-Time CPU Interruptions</h5>
<p>To observe real-time interrupts per second served by the CPU, use this command:</p>
<pre><code class="lang-bash">sar -I SUM 1 3

<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:14:22         INTR    intr/s
19:14:23          sum   5784.00
19:14:24          sum   5694.00
19:14:25          sum   5795.00
Average:          sum   5757.67
</code></pre>
<p>This command helps in monitoring how frequently the CPU is handling interrupts, which can be crucial for real-time performance tuning.</p>
<p>These examples illustrate how you can use <code>sar</code> to monitor various aspects of system performance. Regular use of <code>sar</code> can help in identifying system bottlenecks and ensuring that applications keep running efficiently.</p>
<h3 id="heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</h3>
<p><strong>Why do we need to understand monitoring?</strong></p>
<p>System monitoring is an important aspect of system administration. Critical applications demand a high level of proactiveness to prevent failure and reduce the outage impact.</p>
<p>Linux offers very powerful tools to gauge system health. In this section, you'll learn about the various methods available to check your system's health and identify the bottlenecks.</p>
<h4 id="heading-find-load-average-and-system-uptime">Find load average and system uptime</h4>
<p>System reboots may occur which can sometimes mess up some configurations. To check how long the machine has been up, use the command: <code>uptime</code>. In addition to the uptime, the command also displays load average.</p>
<pre><code class="lang-bash">[user@host ~]$ uptime 19:15:00 up 1:04, 0 users, load average: 2.92, 4.48, 5.20
</code></pre>
<p>Load average is the system load over the last 1, 5, and 15 minutes. A quick glance indicates whether the system load appears to be increasing or decreasing over time.</p>
<p>Note: Ideal CPU queue is <code>0</code>. This is only possible when there are no waiting queues for the CPU.</p>
<p>Per-CPU load can be calculated by dividing load average with the total number of CPUs available.</p>
<p>To find the number of CPUs, use the command <code>lscpu.</code></p>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
.
.
.
output omitted
</code></pre>
<p>If the load average seems to increase and does not come down, the CPUs are overloaded. There is some process that is stuck or there is a memory leakage.</p>
<h4 id="heading-calculating-free-memory">Calculating free memory</h4>
<p>Sometimes, high memory utilization might be causing problems. To check the available memory and the memory in use, use the <code>free</code> command.</p>
<pre><code class="lang-bash">free -mh
<span class="hljs-comment"># output</span>
               total        used        free      shared  buff/cache   available
Mem:            14Gi       3.5Gi       7.7Gi       109Mi       3.2Gi        10Gi
Swap:          8.0Gi          0B       8.0Gi
</code></pre>
<h4 id="heading-calculating-disk-space">Calculating disk space</h4>
<p>To ensure the system is healthy, don't forget about the disk space. To list all the available mount points and their respective used percentage, use the below command. Ideally, utilized disk spaces should not exceed 80%.</p>
<p>The <code>df</code> command provides detailed disk spaces.</p>
<pre><code class="lang-bash">df -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           1.5G  2.4M  1.5G   1% /run
/dev/nvme0n1p2  103G   34G   65G  35% /
tmpfs           7.3G   42M  7.2G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
efivarfs        246K   93K  149K  39% /sys/firmware/efi/efivars
/dev/nvme0n1p3  130G   47G   77G  39% /home
/dev/nvme0n1p1  511M  6.1M  505M   2% /boot/efi
tmpfs           1.5G  140K  1.5G   1% /run/user/1000
</code></pre>
<h4 id="heading-determining-process-states">Determining process states</h4>
<p>Process states can be monitored to see any stuck process with a high memory or CPU usage.</p>
<p>We saw previously that the <code>ps</code> command gives useful information about a process. Have a look at the <code>CPU</code> and <code>MEM</code> columns.</p>
<pre><code class="lang-bash">[user@host ~]$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
 runner         1  0.1  0.0 1535464 15576 ?       S  19:18   0:00 /inject/init
 runner        14  0.0  0.0  21484  3836 pts/0    S   19:21   0:00 bash --norc
 runner        22  0.0  0.0  37380  3176 pts/0    R+   19:23   0:00 ps aux
</code></pre>
<h4 id="heading-real-time-system-monitoring">Real-time system monitoring</h4>
<p>Real time monitoring gives a window into the realtime system state.</p>
<p>One utility you can use to do this is the <code>top</code> command.</p>
<p>The top command displays a dynamic view of the system's processes, displaying a summary header followed by a process or thread list. Unlike its static counterpart <code>ps</code>, <code>top</code> continuously refreshes the system stats.</p>
<p>With <code>top</code>, you can see well-organised details in a compact window. There a number of flags, shortcuts, and highlighting methods that come along with <code>top</code>.</p>
<p>You can also kill processes using <code>top</code>. For that, press <code>k</code> and then enter the process id.</p>
<h4 id="heading-interpreting-logs">Interpreting logs</h4>
<p>System and application logs carry tons of information about what the system is going through. They contain useful information and error codes that point towards errors. If you search for error codes in logs, issue identification and rectification time can be greatly reduced.</p>
<h4 id="heading-network-ports-analysis">Network ports analysis</h4>
<p>The network aspect should not be ignored as network glitches are common and may impact the system and traffic flows. Common network issues include port exhaustion, port choking, unreleased resources, and so on.</p>
<p>To identify such issues, we need to understand port states.</p>
<p>Some of the port states are explained briefly here:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td>LISTEN</td><td>Represents ports that are waiting for a connection request from any remote TCP and port.</td></tr>
<tr>
<td>ESTABLISHED</td><td>Represents connections that are open and data received can be delivered to the destination.</td></tr>
<tr>
<td>TIME WAIT</td><td>Represents waiting time to ensure acknowledgment of its connection termination request.</td></tr>
<tr>
<td>FIN WAIT2</td><td>Represents waiting for a connection termination request from the remote TCP.</td></tr>
</tbody>
</table>
</div><p>Let's explore how we can analyze port-related information in Linux.</p>
<p><strong>Port ranges:</strong> Port ranges are defined in the system, and range can be increased/decreased accordingly. In the below snippet, the range is from <code>15000</code> to <code>65000</code>, which makes a total of <code>50000</code> (65000 - 15000) available ports. If utilized ports are reaching or exceeding this limit, then there is an issue.</p>
<pre><code class="lang-bash">[user@host ~]$ /sbin/sysctl net.ipv4.ip_local_port_range
net.ipv4.ip_local_port_range = 15000    65000
</code></pre>
<p>The error reported in logs in such cases can be <code>Failed to bind to port</code> or <code>Too many connections</code>.</p>
<h4 id="heading-identifying-packet-loss">Identifying packet loss</h4>
<p>In system monitoring, we need to ensure that the outgoing and incoming communication is intact.</p>
<p>One helpful command is <code>ping</code>. <code>ping</code> hits the destination system and brings the response back. Note the last few lines of statistics that show packet loss percentage and time.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># ping destination IP</span>
[user@host ~]$ ping 10.13.6.113
 PING 10.13.6.141 (10.13.6.141) 56(84) bytes of data.
 64 bytes from 10.13.6.113: icmp_seq=1 ttl=128 time=0.652 ms
 64 bytes from 10.13.6.113: icmp_seq=2 ttl=128 time=0.593 ms
 64 bytes from 10.13.6.113: icmp_seq=3 ttl=128 time=0.478 ms
 64 bytes from 10.13.6.113: icmp_seq=4 ttl=128 time=0.384 ms
 64 bytes from 10.13.6.113: icmp_seq=5 ttl=128 time=0.432 ms
 64 bytes from 10.13.6.113: icmp_seq=6 ttl=128 time=0.747 ms
 64 bytes from 10.13.6.113: icmp_seq=7 ttl=128 time=0.379 ms
 ^C
 --- 10.13.6.113 ping statistics ---
 7 packets transmitted, 7 received,0% packet loss, time 6001ms
 rtt min/avg/max/mdev = 0.379/0.523/0.747/0.134 ms
</code></pre>
<p>Packets can also be captured at runtime using <code>tcpdump</code>. We'll look into it later.</p>
<h4 id="heading-gathering-stats-for-issue-post-mortem">Gathering stats for issue post mortem</h4>
<p>It is always a good practice to gather certain stats that would be useful for identifying the root cause later. Usually, after system reboot or services restart, we loose the earlier system snapshot and logs.</p>
<p>Below are some of the methods to capture system snapshot.</p>
<ul>
<li><strong>Logs Backup</strong></li>
</ul>
<p>Before making any changes, copy log files to another location. This is crucial for understanding what condition the system was in during time of issue. Sometimes log files are the only window to look into past system states as other runtime stats are lost.</p>
<ul>
<li><strong>TCP Dump</strong></li>
</ul>
<p>Tcpdump is a command-line utility that allows you to capture and analyze incoming and outgoing network traffic. It is mostly used to help troubleshoot network issues. If you feel that system traffic is being impacted, take <code>tcpdump</code> as follows:</p>
<pre><code class="lang-bash">sudo tcpdump -i any -w

<span class="hljs-comment"># Where,</span>
<span class="hljs-comment"># -i any captures traffic from all interfaces</span>
<span class="hljs-comment"># -w specifies the output filename</span>

<span class="hljs-comment"># Stop the command after a few mins as the file size may increase</span>
<span class="hljs-comment"># use file extension as .pcap</span>
</code></pre>
<p>Once <code>tcpdump</code> is captured, you can use tools like Wireshark to visually analyze the traffic.</p>
<h2 id="heading-810-diagnosing-hardware-problems">8.10 <strong>Diagnosing Hardware Problems</strong></h2>
<p>Troubleshooting unexpected issues is a part of the learning process. Sometimes, you may notice frequent segmentation faults (<code>SIGSEGV</code>), overheating, or random crashes across unrelated applications. The issue could either be software or hardware related. While software-related issues depend on the specific application itself, hardware issues can be diagnosed with some standard steps.</p>
<p>In this section, we will discuss how to diagnose and rule out hardware issues related to memory, CPU, system sensors, power supply, and more.</p>
<h3 id="heading-8101-analyzing-memory-performance"><strong>8.10.1 Analyzing Memory Performance</strong></h3>
<p><strong>Determine Available RAM</strong></p>
<p>If you feel your system is getting slow and taking longer to finish tasks, check your system's available memory. This will ensure there is enough available memory including the swap memory.</p>
<p>The command to check available memory is <code>free -mh</code>, where <code>-h</code> is for human-readable output and <code>-m</code> is for displaying memory in MB.</p>
<pre><code class="lang-bash">free -mh
               total        used        free      shared  buff/cache   available
Mem:            14Gi       5.1Gi       2.4Gi        77Mi       7.3Gi       9.3Gi
Swap:          4.0Gi          0B       4.0Gi
</code></pre>
<p>In the above output, look at the "available" column in the "Mem" row. This shows how much RAM is free for use.</p>
<p>Another way to check the memory in real time is to use the <code>top</code> command. There are 2 ways to do this:</p>
<ul>
<li><p>When you are in <code>top</code>, press <code>Shift + M</code> to sort the processes by memory usage.</p>
</li>
<li><p>Alternately, press <code>m</code> to see the memory usage in a progress bar like format:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739275886121/f1695a67-13d6-4222-b71c-07176a52acb8.png" alt="f1695a67-13d6-4222-b71c-07176a52acb8" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If you see the memory consumed near to <code>100%</code>, you might want to consider identifying the process that is consuming the memory and take necessary action. You might also want to consider adding more memory to your system.</p>
<p><strong>Run a stress test on your hardware</strong></p>
<p>The <code>memtester</code> command is a utility used for diagnosing memory-related issues by stressing the memory and checking for faults. It is often used in situations where you suspect faulty RAM might be causing system instability or crashes.</p>
<p>Here's how to use it effectively:</p>
<ul>
<li><p>First, install <code>memtester</code>.</p>
<pre><code class="lang-bash">  sudo apt install memtester
</code></pre>
</li>
<li><p>Determine the amount of RAM to test and the number of passes you’d like your RAM to go through. In the command below, <code>1G</code> is the amount of RAM to test (1 GB), and <code>5</code> is the number of test passes:</p>
<pre><code class="lang-bash">  sudo memtester 1G 5
</code></pre>
</li>
</ul>
<p>If all tests pass, your RAM is likely error-free. If errors are reported, your RAM might be faulty and could require replacement or further inspection. You can always run the test again with a different amount of RAM or test passes.</p>
<p>Note that, you shouldn't test too much memory at once, as your system also needs memory for running processes. If you have more RAM than can be tested at once, test in smaller segments sequentially.</p>
<p>Below is a snippet of the <code>memtester</code> output if all tests pass. Notice the <code>”ok”</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : ok
  Random Value        : ok
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : ok
  Block Sequential    : ok
  Checkerboard        : ok
  Bit Spread          : ok
  Bit Flip            : ok
  Walking Ones        : ok
  Walking Zeroes      : ok
  8-bit Writes        : ok
  16-bit Writes       : ok
.
.
.
</code></pre>
<p>Below is a snippet of the output if a test fails. Notice the <code>FAILURE</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : testing   1FAILURE: possible bad address line at offset 0x25378a58.
Skipping to next <span class="hljs-built_in">test</span>...
  Random Value        : FAILURE: 0x4df704aaafdf8848 != 0x4df704aaafdfc848 at offset 0x05379a48.
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : testing   6FAILURE: 0x00000000 != 0x00004000 at offset 0x05379a48.
  Block Sequential    : testing   3FAILURE: 0x303030303030303 != 0x303030303034303 at offset 0x05379a48.
  Checkerboard        : testing   0FAILURE: 0xaaaaaaaaaaaaaaaa != 0xaaaaaaaaaaaaeaaa at offset 0x05379a48.
  Bit Spread          : testing  12FAILURE: 0xffffffffffffafff != 0xffffffffffffefff at offset 0x05379a48.
  Bit Flip            : testing   0FAILURE: 0x00000001 != 0x00004001 at offset 0x05379a48.
  Walking Ones        : ok
  Walking Zeroes      : testing   0FAILURE: 0x00000001 != 0x00001001 at offset 0x053af9f8.
  8-bit Writes        : -FAILURE: 0x57c7c8ba7d6f5b3b != 0x57c7c8ba7d6f1b3b at offset 0x0537da28.
  16-bit Writes       : -FAILURE: 0xd7768894fbf79099 != 0xd7768894fbf7d099 at offset 0x05379a48.
FAILURE: 0xfffc5633ffefca5d != 0xfffc5633ffefda5d at offset 0x053a5a38.
.
.
.
</code></pre>
<p>If errors persist across all test loops, it strongly suggests hardware issues, not transient software glitches.</p>
<h3 id="heading-8102-identifying-overheating-issues"><strong>8.10.2 Identifying Overheating Issues</strong></h3>
<p>Overheating can cause unexpected errors and crashes. To diagnose overheating issues, you can use a command line utility <code>lm-sensors</code>.</p>
<p><code>lm-sensors</code> allow syou monitor hardware health by reading data from various sensors. It provides information about system temperatures, voltages, and fan speeds.</p>
<p>Here's how you can identify and monitor your system temperature using <code>lm-sensors</code>:</p>
<ul>
<li><p>First, install <code>lm-sensors</code>:</p>
<pre><code class="lang-bash">  sudo apt install lm-sensors
</code></pre>
</li>
<li><p>Detect the available sensors on your system:</p>
<pre><code class="lang-bash">  sudo sensors-detect
</code></pre>
<p>  Follow the prompts and answer “YES” to detect the available sensors on your system.</p>
</li>
<li><p>Once the available sensors are detected, you can view the temperature of your system using the <code>sensors</code> command:</p>
<pre><code class="lang-bash">  sensors
</code></pre>
<p>  In the output below, you can see the temperature reading at the edge of the GPU, which is 41.0 degrees Celsius. You can also see other pieces of information like voltage supplied, power consumption and voltage supplied.</p>
<pre><code class="lang-bash">  amdgpu-pci-0400
  Adapter: PCI adapter
  vddgfx:      731.00 mV 
  vddnb:       687.00 mV 
  edge:         +41.0°C  
  PPT:           7.00 W
</code></pre>
<p>  Using <code>lm-sensors</code> ensures that the system is operating within safe parameters. It helps to detect potential hardware problems early and take corrective actions to prevent hardware damage.</p>
</li>
</ul>
<h3 id="heading-8103-evaluating-hard-drive-health"><strong>8.10.3 Evaluating Hard Drive Health</strong></h3>
<p>Disk errors can also cause application crashes. To identify disk issues, you can run disk check using <code>smartmontools</code>:</p>
<ul>
<li><p>First, install <code>smartmontools</code>:</p>
<pre><code class="lang-bash">  sudo apt install smartmontools
</code></pre>
</li>
<li><p>Run a quick health check using the command below and replace <code>/dev/sdX</code> with your disk name (check with <code>lsblk</code>).</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/sdX
</code></pre>
</li>
<li><p>Here is the result I got when I ran the command on my disk <code>/dev/nvme0n1</code>:</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/nvme0n1
  smartctl 7.4 2023-08-01 r5530 [x86_64-linux-6.8.0-52-generic] (<span class="hljs-built_in">local</span> build)
  Copyright (C) 2002-23, Bruce Allen, Christian Franke, www.smartmontools.org

  === START OF SMART DATA SECTION ===
  SMART overall-health self-assessment <span class="hljs-built_in">test</span> result: PASSED
</code></pre>
</li>
<li><p>You can also run a detailed test:</p>
<pre><code class="lang-bash">  sudo smartctl -a /dev/nvme0n1
</code></pre>
</li>
</ul>
<p>The detailed test provides a full report, including:</p>
<ul>
<li><p>Temperature</p>
</li>
<li><p>Power-on hours</p>
</li>
<li><p>Error counts</p>
</li>
<li><p>Wear leveling (for SSDs), and more.</p>
</li>
</ul>
<h3 id="heading-8104-conducting-a-cpu-stress-test"><strong>8.10.4 Conducting a CPU Stress Test</strong></h3>
<p>Faulty CPUs can also lead to a number of performance issues. To test your CPU, you can use the <code>stress-ng</code> utility:</p>
<ul>
<li><p>Install <code>stress-ng</code>:</p>
<pre><code class="lang-bash">  sudo apt install stress-ng
</code></pre>
</li>
<li><p>Run a CPU stress test:</p>
<pre><code class="lang-bash">  stress-ng --cpu 4 --timeout 60
</code></pre>
</li>
</ul>
<p>In the above command, <code>4</code> is the number of CPU cores you’d like to test and <code>60</code> is the duration in seconds. The command will stress all 4 CPU cores for 60 seconds. Notice the CPU is at <code>100%</code> load during the test:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739277374316/9ab475c2-7f09-4c40-989b-e474e334935c.png" alt="9ab475c2-7f09-4c40-989b-e474e334935c" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If the system crashes during this test, the CPU may be faulty.</p>
<h3 id="heading-8105-examining-system-logs-for-errors"><strong>8.10.5 Examining System Logs for Errors</strong></h3>
<p><code>systemd</code> is a Linux system manager responsible for booting the system, managing system processes, and handling system services.</p>
<p><code>journalctl</code> is a command to query the <code>systemd</code> journal logs. It provides detailed logging for system processes, kernel events, user applications, and more.</p>
<p>You can check system logs for hardware-related errors using the command: <code>journalctl -k | grep -iE "error|fault|panic"</code>.</p>
<p>In the logs, look for messages about:</p>
<ul>
<li><p>Memory faults.</p>
</li>
<li><p>I/O errors.</p>
</li>
<li><p>Hardware timeouts.</p>
</li>
</ul>
<p>Here is what errors in the log file can look like:</p>
<pre><code class="lang-bash">Feb 11 10:15:32 hostname kernel: [Hardware Error]: CPU 0: Machine Check: 0 Bank 4: b200000000070f0f
Feb 11 10:15:32 hostname kernel: [Hardware Error]: TSC 0 ADDR fef1c000 MISC 38a0000086 
Feb 11 10:15:32 hostname kernel: [Hardware Error]: PROCESSOR 0:306a9 TIME 1613045732 SOCKET 0 APIC 0 microcode 1f
Feb 11 10:16:45 hostname kernel: EXT4-fs error (device sda1): ext4_find_entry:1453: inode <span class="hljs-comment">#2: comm ls: reading directory lblock 0</span>
Feb 11 10:17:12 hostname kernel: [drm:drm_atomic_helper_commit_cleanup_done [drm_kms_helper]] *ERROR* [CRTC:36:pipe A] flip_done timed out
Feb 11 10:18:05 hostname kernel: Kernel panic - not syncing: Fatal exception
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Thank you for reading the book until the end. If you found it helpful, consider sharing it with others.</p>
<p>This book doesn't end here, though. I will continue to improve it and add new materials in the future. If you found any issues or if you would like to suggest any improvements, <a target="_blank" href="https://github.com/zairahira/Mastering-Linux-Handbook">feel free to open a PR/ Issue.</a></p>
<p><strong>Stay Connected and Continue Your Learning Journey!</strong></p>
<p>Your journey with Linux doesn't have to end here. Stay connected and take your skills to the next level:</p>
<ol>
<li><p><strong>Follow Me on Social Media</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/hira_zaira">X</a>: I share useful short form content there. My DMs are always open.</p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/zaira-hira/">LinkedIn</a>: I share articles and posts on tech there. Leave a recommendation on LinkedIn and endorse me on relevant skills.</p>
</li>
</ul>
</li>
<li><p><strong>Get access to exclusive content</strong>: For one-on-one help and exclusive content go <a target="_blank" href="https://buymeacoffee.com/zairah/extras">here</a>.</p>
</li>
</ol>
<p>My <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">articles</a> and books, like this one, are part of my mission to increase accessibility to quality content for everyone. This book will also be open to translation in other languages. Each piece takes a lot of time and effort to write. This book will be free, forever. If you've enjoyed my work and want to keep me motivated, consider <a target="_blank" href="https://buymeacoffee.com/zairah">buying me a coffee</a>.</p>
<p>Thank you once again and happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Do Numerical Conversions Work in Computer Systems? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Computers perform complex calculations when carrying out their assigned tasks. At the very core, the calculations boil down to operations like comparisons, assignments, and addition. Have you ever wondered how they are performed under the hood and wh... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-do-numerical-conversions-work/</link>
                <guid isPermaLink="false">66578856935992fb202d9272</guid>
                
                    <category>
                        <![CDATA[ Computers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 29 May 2024 19:56:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715271341530/60608a00-2e63-434e-91e8-c766b171f6f7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Computers perform complex calculations when carrying out their assigned tasks. At the very core, the calculations boil down to operations like comparisons, assignments, and addition.</p>
<p>Have you ever wondered how they are performed under the hood and why they are important? At a fundamental level, a computer works by performing various numerical conversions.</p>
<p>In this article, you'll learn the following concepts:</p>
<ul>
<li><p>The importance of numerical systems in computers.</p>
</li>
<li><p>Types of numerical systems.</p>
</li>
<li><p>Numerical conversion techniques.</p>
</li>
<li><p>Application of different numerical systems.</p>
</li>
<li><p>Mini exercises to keep you engaged along the way.</p>
</li>
</ul>
<h2 id="heading-types-of-numerical-systems">Types of Numerical Systems</h2>
<p>Numerical conversion is the process of converting numbers from one numeral system to another. In computer systems, the common numeral systems include decimal (base-10), binary (base-2), hexadecimal (base-16), and octal (base-8).</p>
<h3 id="heading-but-what-is-a-base">But What Is a Base?</h3>
<p>In mathematics and computer science, the term "base" refers to the number of unique digits or symbols used in a positional numeral system. Each digit's value is multiplied by the base raised to the power of its position in the number, starting from the rightmost digit, which represents the units place.</p>
<p>Here's an explanation of the commonly encountered numeral systems:</p>
<ol>
<li><p><strong>Base-2 (Binary)</strong>:</p>
<ul>
<li><p>Base-2, or binary, uses only two symbols: 0 and 1.</p>
</li>
<li><p>Each digit's value is a power of 2, with positions increasing from right to left.</p>
</li>
</ul>
</li>
<li><p><strong>Base-10 (Decimal)</strong>:</p>
<ul>
<li><p>Base-10, or decimal uses ten symbols from 0 to 9.</p>
</li>
<li><p>Each digit's value is a power of 10, with positions increasing from right to left.</p>
</li>
</ul>
</li>
<li><p><strong>Base-8 (Octal)</strong>:</p>
<ul>
<li><p>Base-8, or octal, uses eight symbols: 0 to 7.</p>
</li>
<li><p>Each digit's value is a power of 8, with positions increasing from right to left.</p>
</li>
</ul>
</li>
<li><p><strong>Base-16 (Hexadecimal)</strong>:</p>
<ul>
<li><p>Base-16, or hexadecimal, uses sixteen symbols: 0 to 9 and A to F (representing 10 to 15).</p>
</li>
<li><p>Each digit's value is a power of 16, with positions increasing from right to left.</p>
</li>
<li><p>Below is a table showing the mapping of hexadecimal numbers from 10 with alphabets.</p>
</li>
</ul>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Character</td><td>Hexadecimal</td></tr>
</thead>
<tbody>
<tr>
<td>A</td><td>10</td></tr>
<tr>
<td>B</td><td>11</td></tr>
<tr>
<td>C</td><td>12</td></tr>
<tr>
<td>D</td><td>13</td></tr>
<tr>
<td>E</td><td>14</td></tr>
<tr>
<td>F</td><td>15</td></tr>
</tbody>
</table>
</div><p>This notation is commonly used to simplify the representation of binary-coded values.</p>
<h2 id="heading-importance-of-understanding-numerical-systems-in-computers">Importance of Understanding Numerical Systems in Computers</h2>
<p>Learning numeral conversions in computer science is essential for several reasons:</p>
<ol>
<li><p><strong>Understanding Data Representation</strong>: Computers store and manipulate data using binary (base-2) representation. Knowing how to convert between numeral systems helps in understanding how data is stored and processed at the fundamental level.</p>
</li>
<li><p><strong>Addressing Memory</strong>: Memory addresses in computers are frequently represented in hexadecimal format. Knowing how to convert between decimal and hexadecimal is crucial for understanding memory management and for debugging.</p>
</li>
<li><p><strong>Networking and Communication</strong>: In networking, IP addresses and MAC addresses are often represented in hexadecimal format. Understanding hexadecimal conversion is thus comes in handy for networking professionals.</p>
</li>
<li><p><strong>Cryptography</strong>: In cryptography, hexadecimal numbers are frequently used to represent keys, cipher texts, and other cryptographic data. Understanding numeral conversions helps in understanding cryptographic operations.</p>
</li>
</ol>
<h2 id="heading-conversion-techniques">Conversion Techniques</h2>
<p>In this section, you'll learn techniques to convert one number system to another.</p>
<h3 id="heading-decimal-to-binary">Decimal to Binary</h3>
<p><strong>Step-by-Step Conversion Process:</strong></p>
<ol>
<li><p><strong>Divide the number by 2:</strong> The first step is to divide the number by 2 and record the remainder.</p>
</li>
<li><p><strong>Divide the quotient by 2 repetitively:</strong> Divide the quotient from step 1 and record the remainder. Continue to divide and record the remainder till 1 remains as the quotient.</p>
</li>
<li><p><strong>Find the solution in reverse order:</strong> Starting from the last quotient that would be <code>1</code>, go upwards to get the final answer.</p>
</li>
</ol>
<p><strong>Example Conversion:</strong></p>
<p>Let's say you want the binary equivalent of <code>17</code>, then the process would be like this:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Result</td><td>Remainder</td></tr>
</thead>
<tbody>
<tr>
<td>17/2</td><td>8</td><td>1 ⬆️</td></tr>
<tr>
<td>8/2</td><td>4</td><td>0 ⬆️</td></tr>
<tr>
<td>4/2</td><td>2</td><td>0 ⬆️</td></tr>
<tr>
<td>2/2</td><td>1 ➡️</td><td>0 ⬆️</td></tr>
</tbody>
</table>
</div><p>To find the final answer, follow the arrows. Start from the bottom where the result is <code>1</code> and go upwards. You'll get <code>10001</code>.</p>
<p>So,</p>
<p>$$17_{10} = 10001_{2}$$</p><p>Let's try a bigger number <code>55</code></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Result</td><td>Remainder</td></tr>
</thead>
<tbody>
<tr>
<td>55/2</td><td>27</td><td>1 ⬆️</td></tr>
<tr>
<td>27/2</td><td>13</td><td>1 ⬆️</td></tr>
<tr>
<td>13/2</td><td>6</td><td>1 ⬆️</td></tr>
<tr>
<td>6/2</td><td>3</td><td>0 ⬆️</td></tr>
<tr>
<td>3/2</td><td>1 ➡️</td><td>1 ⬆️</td></tr>
</tbody>
</table>
</div><p>So,</p>
<p>$$55_{10} = 110111_{2}$$</p><h4 id="heading-now-your-turn">Now, your turn:</h4>
<p>What is <code>67</code> in binary?</p>
<details><summary>Show Answer</summary><div data-type="detailsContent"><code>67</code> in binary is <code>1000011</code>.</div></details>

<h3 id="heading-binary-to-decimal">Binary to Decimal</h3>
<p><strong>Step-by-Step Conversion Process:</strong></p>
<ol>
<li><p><strong>Write down the binary number</strong>: Separate each bit for clarity.</p>
</li>
<li><p><strong>Map each bit with its corresponding power of 2</strong>: Start from <code>2^0</code> on the right and increase the exponent by <code>1</code> as you move left.</p>
</li>
<li><p><strong>Multiply each bit by its corresponding power of 2</strong>: If the bit is 1, multiply it by the power of 2 for that position. If the bit is 0, the result is 0 for that position.</p>
</li>
<li><p><strong>Sum all the products</strong>: Add all the results from step 3 to get the decimal equivalent.</p>
</li>
</ol>
<p><strong>Example Conversion:</strong></p>
<p>For <code>101</code>, the conversion would be like this:</p>
<p>$$\begin{align} &amp;1\times2^2 + 0\times2^1 + 1\times2^0 \newline &amp;= 4 + 0 + 1 \newline &amp;= 5 \end{align}$$</p><p>So,</p>
<p>$$101_{2} = 5_{10}$$</p><p>Let's convert <code>1011001</code> to decimal:</p>
<p>$$\begin{align} &amp;1\times2^6+0\times2^5+1\times2^4+1\times2^3+0\times2^2+0\times2^1+1\times2^0\newline &amp;= 64+0+16+8+0+0+1 \newline &amp;= 89 \end{align}$$</p><p>So,</p>
<p>$$1011001_{2} = 89_{10}$$</p><h3 id="heading-binary-to-hexadecimal">Binary to Hexadecimal</h3>
<p><strong>Step-by-Step Conversion Process:</strong></p>
<ol>
<li><p><strong>Make pairs of 4:</strong> Segregate the given binary number into 4 bits each, starting from the rightmost bit.</p>
</li>
<li><p><strong>Pad in 0 to the left-most pair if the bits do not count to 4:</strong> If the leftmost part doesn't make 4 bits, add zeros to the left of it to complete the count.</p>
</li>
<li><p><strong>Find equivalent decimal number as explained previously:</strong> Use binary to decimal conversion.</p>
</li>
</ol>
<p><strong>Example Conversion:</strong></p>
<p>Let's convert <code>10010010</code> to hexadecimal.</p>
<ol>
<li><p>Split the bits into sections of 4 bits each, starting from the rightmost bit:</p>
<ul>
<li><p><code>10010010</code> = [<code>1001][0010]</code></p>
</li>
<li><p>Padding was not needed here as each section is 4 bits long.</p>
</li>
</ul>
</li>
<li><p>Convert binary to decimal:</p>
</li>
</ol>
<p>$$\begin{align} &amp;[1001][0010]\newline &amp;=[1\times2^3 + 0\times2^2 + 0\times2^1 + 1\times2^0] [0\times2^3 + 0\times2^2 + 1\times2^1 + 1\times2^0] \newline &amp;=[8+0+0+1][0+0+1+1] = [9][2] \end{align}$$</p><p>So,</p>
<p>$$10010010_{2} = 92_{16}$$</p><p>Let's run another example. But first,</p>
<p>Recall that, the numbers 10 - 15 are represented as follows in hexadecimal:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Character</td><td>Hexadecimal</td></tr>
</thead>
<tbody>
<tr>
<td>A</td><td>10</td></tr>
<tr>
<td>B</td><td>11</td></tr>
<tr>
<td>C</td><td>12</td></tr>
<tr>
<td>D</td><td>13</td></tr>
<tr>
<td>E</td><td>14</td></tr>
<tr>
<td>F</td><td>15</td></tr>
</tbody>
</table>
</div><p>Let's convert <code>11010011011</code> to hexadecimal.</p>
<ol>
<li><p>Divide the bits into groups of 4, starting from the right.</p>
<ul>
<li>[110][1001][1011]</li>
</ul>
</li>
<li><p>Add padding of <code>0</code> to the leftmost section.</p>
<ul>
<li>[0110][1001][1011]</li>
</ul>
</li>
<li><p>Convert the bits to decimal using the binary-to-decimal method.</p>
</li>
</ol>
<p>$$\begin{align} &amp;[0110][1001][1011]\newline &amp;=[0\times2^3+1\times2^2+1\times2^1+0\times2^0]\ [1\times2^3+0\times2^2+0\times2^1+1\times2^0]\ [1\times2^3+0\times2^2+1\times2^1+1\times2^0]\newline &amp;=[6][9][11]\newline &amp;=[6][9][B] \end{align}$$</p><ol start="4">
<li><p>As <code>11</code> maps to <code>B</code> in hexadecimal, replace <code>11</code> with <code>B</code> .</p>
<p> $$[6][9][11] =[6][9][B]$$</p>
</li>
</ol>
<p>So,</p>
<p>$$11010011011_{2} = 69B_{16}$$</p><h3 id="heading-hexadecimal-to-binary">Hexadecimal to Binary</h3>
<p><strong>Step-by-Step Conversion Process:</strong></p>
<p><strong>Example Conversion:</strong></p>
<ol>
<li><p><strong>Identify Each Hexadecimal Digit</strong>: Break down the hexadecimal number into individual digits.</p>
</li>
<li><p><strong>Convert Each Hexadecimal Digit to Binary</strong>: Each hexadecimal digit corresponds to a unique four-bit binary sequence.</p>
</li>
</ol>
<h3 id="heading-example-conversion"><strong>Example Conversion:</strong></h3>
<p>Let's convert the hexadecimal number <code>2F3</code> to binary.</p>
<ol>
<li><p><strong>Identify Each Hexadecimal Digit</strong>:</p>
<ul>
<li><p><code>2</code></p>
</li>
<li><p><code>F</code></p>
</li>
<li><p><code>3</code></p>
</li>
</ul>
</li>
<li><p><strong>Convert Each Hexadecimal Digit to Binary</strong>:</p>
<ul>
<li><p><code>2</code> in binary: <code>0010</code></p>
</li>
<li><p><code>F</code> is <code>15</code> in decimal and in binary: <code>1111</code></p>
</li>
<li><p><code>3</code> in binary: <code>0011</code></p>
</li>
</ul>
</li>
<li><p><strong>Combine the Binary Sequences</strong>:</p>
<ul>
<li><code>2F3</code> in binary: <code>0010 1111 0011</code></li>
</ul>
</li>
</ol>
<p>So, the hexadecimal number <code>2F3</code> converts to <code>001011110011</code> in binary.</p>
<h3 id="heading-octal-to-binary">Octal to Binary</h3>
<p><strong>Step-by-Step Conversion Process:</strong></p>
<p><strong>Example Conversion:</strong></p>
<p>To convert an octal number to binary, each octal digit (0-7) is converted to a three-bit binary number because the largest octal digit (7) can be represented using three bits (111).</p>
<h3 id="heading-step-by-step-conversion-process"><strong>Step-by-Step Conversion Process:</strong></h3>
<ol>
<li><p><strong>Identify Each Octal Digit</strong>: Break down the octal number into individual digits.</p>
</li>
<li><p><strong>Convert Each Octal Digit to Binary</strong>: Use the same decimal-to-binary conversion method.</p>
</li>
<li><p><strong>Combine the Binary Sequences</strong>: Each sequence should be 3 bits, pad zeros to the left if needed. Concatenate the three-bit binary sequences to form the final binary number.</p>
</li>
</ol>
<h3 id="heading-example-conversion-1"><strong>Example Conversion:</strong></h3>
<p>Let's convert the octal number <code>157</code> to binary.</p>
<ol>
<li><p><strong>Identify Each Octal Digit</strong>:</p>
<ul>
<li><p><code>1</code></p>
</li>
<li><p><code>5</code></p>
</li>
<li><p><code>7</code></p>
</li>
</ul>
</li>
<li><p><strong>Convert Each Octal Digit to Binary</strong>:</p>
<ul>
<li><p><code>1</code> in binary: <code>001</code></p>
</li>
<li><p><code>5</code> in binary: <code>101</code></p>
</li>
<li><p><code>7</code> in binary: <code>111</code></p>
</li>
</ul>
</li>
<li><p><strong>Combine the Binary Sequences</strong>:</p>
<ul>
<li><code>157</code> in binary: <code>001 101 111</code></li>
</ul>
</li>
</ol>
<p>So, the octal number <code>157</code> converts to <code>001101111</code> in binary.</p>
<h3 id="heading-binary-to-octal">Binary to Octal</h3>
<p>To convert a binary number to an octal, group the binary digits into sets of three, starting from the right to the left. You can pad that group with leading zeros if the left-most group isn't 3 digits.</p>
<h3 id="heading-step-by-step-conversion-process-1"><strong>Step-by-Step Conversion Process:</strong></h3>
<ol>
<li><p><strong>Pad the Binary Number with Leading Zeros</strong> (if necessary) to make the number of digits in groups of three:</p>
<ul>
<li><p>Binary: <code>11010011</code></p>
</li>
<li><p>Padded Binary: <code>011 010 011</code></p>
</li>
</ul>
</li>
<li><p><strong>Group the Binary Digits into Sets of Three</strong>:</p>
<ul>
<li>Groups: <code>011 010 011</code></li>
</ul>
</li>
<li><p><strong>Convert Each Group of Three Binary Digits to Its Octal Equivalent</strong>:</p>
<ul>
<li>Use the same method as binary to decimal.</li>
</ul>
</li>
<li><p><strong>Combine the Octal Digits</strong>: Form the final octal number by combining the octal digits.</p>
</li>
</ol>
<h3 id="heading-example-conversion-2"><strong>Example Conversion:</strong></h3>
<p>Let's convert the binary number <code>11010011</code> to octal.</p>
<ol>
<li><p><strong>Pad the Binary Number with Leading Zeros</strong> (if necessary):</p>
<ul>
<li><p>Binary: <code>11010011</code></p>
</li>
<li><p>Padded Binary: <code>011 010 011</code></p>
</li>
</ul>
</li>
<li><p><strong>Group the Binary Digits into Sets of Three</strong>:</p>
<ul>
<li>Groups: <code>011 010 011</code></li>
</ul>
</li>
<li><p><strong>Convert Each Group of Three Binary Digits to Its Octal Equivalent</strong>:</p>
<ul>
<li><p><code>011</code> (binary) = <code>3</code> (octal)</p>
</li>
<li><p><code>010</code> (binary) = <code>2</code> (octal)</p>
</li>
<li><p><code>011</code> (binary) = <code>3</code> (octal)</p>
</li>
</ul>
</li>
<li><p><strong>Combine the Octal Digits</strong>:</p>
<ul>
<li><code>11010011</code> in octal: <code>323</code></li>
</ul>
</li>
</ol>
<p>So, the binary number <code>11010011</code> converts to <code>323</code> in octal.</p>
<h2 id="heading-applications-of-numerical-conversions">Applications of Numerical Conversions</h2>
<p>In this section, you'll learn about two common applications of numerical conversions.</p>
<h3 id="heading-file-permissions">File permissions</h3>
<p>Octal notation is commonly used in file permission management in Unix-like operating systems. In Unix systems, each file has associated permissions that determine who can read, write, or execute the file. These permissions are represented by a 3-digit octal number, where each digit corresponds to a specific set of permissions: <code>owner</code>, <code>group</code>, and <code>others</code>.</p>
<p>Each digit in the octal representation is composed of three bits, with each bit representing a specific permission:</p>
<ul>
<li><p>The first digit represents permissions for the file owner.</p>
</li>
<li><p>The second digit represents permissions for the group associated with the file.</p>
</li>
<li><p>The third digit represents permissions for others (users not in the owner group).</p>
</li>
</ul>
<p>The mapping of permissions to bits is as follows:</p>
<ul>
<li><p>Read permission corresponds to the value <code>4.</code></p>
</li>
<li><p>Write permission corresponds to the value <code>2</code>.</p>
</li>
<li><p>Execute permission corresponds to the value <code>1</code>.</p>
</li>
</ul>
<p>To calculate the octal representation of permissions, you sum the values of the granted permissions. For example:</p>
<ul>
<li>If a file has read and write permissions for the owner, read-only permissions for the group, and no permissions for others, the octal representation would be <code>640</code>.</li>
</ul>
<p>Here's the breakdown:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Permission</td><td>Owner</td><td>Group</td><td>Others</td></tr>
</thead>
<tbody>
<tr>
<td>Read = 4</td><td>Yes</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Write = 2</td><td>Yes</td><td>No</td><td>No</td></tr>
<tr>
<td>Execute = 1</td><td>No</td><td>No</td><td>No</td></tr>
<tr>
<td></td><td>4 +2 + 0 = 6</td><td>4 +0 + 0 = 4</td><td>0</td></tr>
</tbody>
</table>
</div><ul>
<li><p>The owner has read (4) + write (2) permissions, resulting in 6.</p>
</li>
<li><p>The group has read (4) permissions only.</p>
</li>
<li><p>Others have no permissions, which corresponds to 0.</p>
</li>
</ul>
<p>So, the permissions for the file in octal representation are <code>640</code>.</p>
<p><strong>Quiz:</strong></p>
<details><summary>What does the permission 777 show?</summary><div data-type="detailsContent">Read, write and execute for all- users, groups and others.</div></details>

<p>This octal representation of permissions provides a concise and efficient way to manage file permissions in Unix systems, allowing for easy understanding and manipulation of access rights.</p>
<p>To learn more about file permissions, you can read my other article <a target="_blank" href="https://www.freecodecamp.org/news/linux-chmod-chown-change-file-permissions/">here</a>.</p>
<h3 id="heading-color-codes">Color codes</h3>
<p>You might have noticed that the notation <code>#ffffff</code>, <code>#c3c400</code> are prevalent in various digital contexts, such as web design, graphics editing software, and programming. As you might have guessed, this is a hexadecimal representation. As an example, see this palette from <a target="_blank" href="https://colorhunt.co/palette/ffff80ffaa80ff5580ff0080">Colorhunt</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715250432475/ccab919f-3796-441a-89e7-60fc3a85e01c.png" alt="ccab919f-3796-441a-89e7-60fc3a85e01c" class="image--center mx-auto" width="634" height="205" loading="lazy"></p>
<p>Here we have a hexadecimal value of the color followed by the equivalent RGB value.</p>
<p>Hexadecimal color codes represent colors in the RGB model using pairs of hexadecimal digits for each color component (red, green, and blue). Each pair corresponds to an 8-bit value, ranging from <code>00</code> to <code>FF</code>, where <code>00</code> represents the lowest intensity(black) and <code>FF</code> represents the highest intensity(white).</p>
<p>For instance, <code>#FF0000</code> stands for red, <code>#00FF00</code> stands for green, and <code>#0000FF</code> stands for blue.</p>
<p><strong>QUIZ:</strong></p>
<details><summary>If red and green makes yellow in RGB model, what would be the hex equivalent?</summary><div data-type="detailsContent">#ffff00</div></details>

<h2 id="heading-conclusion">Conclusion</h2>
<p>By the end of this article, you should be comfortable with carrying out most of the common conversions. In this article, you:</p>
<ul>
<li><p>Explored the importance of numerical conversions in computers.</p>
</li>
<li><p>Explored numeral systems like binary, decimal, hexadecimal, and octal.</p>
</li>
<li><p>Learned conversion techniques between these systems.</p>
</li>
<li><p>Understood some practical applications of numeral systems in computing.</p>
</li>
</ul>
<h2 id="heading-next-steps">Next steps</h2>
<p>You can code a decimal to binary converter in JavaScript by following <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/learn-recursion-by-building-a-decimal-to-binary-converter/step-1">this</a> step-by-step guide.</p>
<p>I hope you found this article helpful. I would love to connect with you on any of these <a target="_blank" href="https://zaira_.bio.link/">platforms</a>.</p>
<p>See you in the next tutorial, happy coding 😁</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Diagrams as Code with Mermaid, GitHub, and Visual Studio Code ]]>
                </title>
                <description>
                    <![CDATA[ Diagrams are an important part of technical documentation. In this article we will explore how we can use code to generate diagrams and leverage them in Markdown. Here is an example of how a code generated diagram looks like: Diagram generated by co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/diagrams-as-code-with-mermaid-github-and-vs-code/</link>
                <guid isPermaLink="false">66adea301ad24d82983fd24b</guid>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ documentation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 06 Sep 2023 20:51:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/mermaid-code-as-a-diagram.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Diagrams are an important part of technical documentation. In this article we will explore how we can use code to generate diagrams and leverage them in Markdown.</p>
<p>Here is an example of how a code generated diagram looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Untitled-design--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Diagram generated by code</em></p>
<p>No tools, no dragging, aligning and snapping shapes to places. Just code. Interesting right?</p>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<p>To follow along with this tutorial, you should have the following:</p>
<ul>
<li><p>A basic understanding of Markdown. Have a look at <a target="_blank" href="https://www.freecodecamp.org/news/markdown-cheat-sheet/">this guide</a> if you aren't familiar with Markdown.</p>
</li>
<li><p>Visual Studio Code with a Markdown previewing extension (covered in detail in coming sections).</p>
</li>
<li><p>GitHub, to understand how you can render diagrams there.</p>
</li>
</ul>
<h2 id="heading-advantages-of-generating-diagrams-as-code">Advantages of Generating Diagrams as Code</h2>
<p>There are several advantages of generating diagrams as code rather than using traditional methods to manually 'create' diagrams. Let's see some of them:</p>
<ul>
<li><p><strong>Dynamic</strong>: Code-generated diagrams are dynamic which means that you can easily update them by updating the code.</p>
</li>
<li><p><strong>Editable</strong>: With code-generated images, you are not relying on complex image generating tools. You can simply edit the code in a text editor and get an updated image.</p>
</li>
<li><p><strong>Efficient</strong>: Code-generated images are fast to load compared to static images. Also you don't need to host them separately as an image in your website.</p>
</li>
<li><p><strong>Quick to create</strong>: You can use a template and quickly come up with diagrams just using code. You don't need to invest the time and effort in learning image creation tools, that are usually overwhelming to start with.</p>
</li>
</ul>
<h2 id="heading-how-to-render-and-view-mermaid-code">How to Render and View Mermaid Code</h2>
<p>There are several ways you can create and view Mermaid diagrams.</p>
<h3 id="heading-vscode">VSCode</h3>
<p>First, install a Markdown previewer that has the support for Mermaid. Here is an example of such an extension: <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid">Markdown Preview Mermaid Support</a>.</p>
<p>Create an empty Markdown file using the extension <code>.md</code>. Write your code in this file and open the preview on the right pane:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-226.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Code and preview in VSCode</em></p>
<h3 id="heading-stackedit">StackEdit</h3>
<p><a target="_blank" href="https://stackedit.io/">StackEdit</a> is an online, browser-based Markdown previewer. It provides an editor window and a preview on the right side.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173257560/a5cf3d3d-7db4-4176-a1b8-fc59597d5966.png" alt="a5cf3d3d-7db4-4176-a1b8-fc59597d5966" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Code and preview in StackEdit</em></p>
<h3 id="heading-github">GitHub</h3>
<p>You can add Mermaid diagrams to create compelling README files in GitHub. Simply edit the <code>README.md</code> or any other Markdown file in GitHub to render Mermaid diagrams.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Edit code in GitHub</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>View and render Mermaid diagram in GitHub</em></p>
<h2 id="heading-how-to-generate-diagrams-as-code-with-mermaid">How to Generate Diagrams as Code with Mermaid</h2>
<p>Mermaid is a JavaScript-based tool that transforms Markdown-style text into dynamic diagrams, allowing you to create and modify them effortlessly.</p>
<p>Mermaid makes it easy to generate diagrams and visuals using simple text and code.</p>
<p>It follows a simple syntax:</p>
<pre><code class="lang-bash">```mermaid
    your code goes here
    .
    .
    .

```
</code></pre>
<p>With Mermaid, you can generate the following diagram types:</p>
<ul>
<li><p>Flowchart</p>
</li>
<li><p>Sequence Diagram</p>
</li>
<li><p>Class Diagram</p>
</li>
<li><p>Gantt</p>
</li>
<li><p>Pie Chart</p>
</li>
</ul>
<p>Let's explore them one by one.</p>
<h3 id="heading-how-to-create-a-flowchart">How to Create a Flowchart</h3>
<p>A flowchart is a picture that shows the steps of a process using symbols, helping to explain the process in a clear and organized way. A flow chart is composed of nodes that are connected by arrows.</p>
<p>You can render flowcharts in mermaid using this example:</p>
<pre><code class="lang-bash">```mermaid
flowchart TD;
    A[Start] --&gt; B[Process 1];
    B --&gt; C[Process 2];
    C --&gt; D[End];
```
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173454651/613d31f6-102b-4a62-a24a-0360e5c32ca5.png" alt="613d31f6-102b-4a62-a24a-0360e5c32ca5" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Flowcharts in mermaid</em></p>
<p><strong>Syntax breakdown:</strong></p>
<ul>
<li><p><code>flowchart</code>: This keyword tells that we are creating a flowchart.</p>
</li>
<li><p><code>TD</code>: this is the orientation of the flowchart and stands for Top to Down. The other FlowChart orientations are:<br>  – <code>TB</code> - Top to bottom,same as TD.<br>  – <code>BT</code> - Bottom to top<br>  – <code>RL</code> - Right to left<br>  – <code>LR</code> - Left to right</p>
</li>
<li><p><code>--&gt;</code>: The direction of the arrow connecting the nodes.</p>
</li>
</ul>
<h3 id="heading-how-to-create-a-sequence-diagram"><strong>How to Create a Sequence Diagram</strong></h3>
<p>A sequence diagram is an illustrative representation of interactions between processes, demonstrating their operational flow and the sequence of execution.</p>
<p>You can render sequence diagrams in mermaid using this syntax:</p>
<pre><code class="lang-bash">```mermaid
sequenceDiagram
    participant Client
    participant Server
    Client-&gt;&gt;Server: Register user
    activate Server
    Server--&gt;&gt;Client: User already exists.
    deactivate Server

```
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173517259/9abf9118-8eb5-4203-ac16-c188d40a3e1f.png" alt="9abf9118-8eb5-4203-ac16-c188d40a3e1f" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Sequence diagram in mermaid</em></p>
<p><strong>Syntax breakdown:</strong></p>
<ul>
<li><p><code>sequenceDiagram</code>: This keyword specifies that we are making a sequence diagram.</p>
</li>
<li><p><code>participant</code>: These are the participants or the actors in a sequence diagram.</p>
</li>
<li><p><code>activate/ deactivate</code>: It is possible to activate and deactivate an actor. Activation shows as a small rectangle between interactions.</p>
</li>
<li><p><code>--&gt;&gt;</code>: Connecting lines (dashed).</p>
</li>
<li><p><code>-&gt;</code>: Connecting lines (solid).</p>
</li>
</ul>
<h3 id="heading-how-to-create-a-class-diagram"><strong>How to Create a Class Diagram</strong></h3>
<p>Class diagrams are used to visualize the structure and relationships of classes, interfaces, and their interactions in object-oriented programming (OOP). You can render class diagrams in Mermaid using this syntax:</p>
<pre><code class="lang-bash">```mermaid
classDiagram
    class Animal {
        +name: string
        +age: int
        +makeSound(): void
    }

    class Dog {
        +breed: string
        +bark(): void
    }

    class Cat {
        +color: string
        +meow(): void
    }

    Animal &lt;|-- Dog
    Animal &lt;|-- Cat

```
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173586580/980dadee-760a-4593-9a73-fbddb6ea7d41.png" alt="980dadee-760a-4593-9a73-fbddb6ea7d41" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Class diagram in mermaid</em></p>
<p><strong>Syntax breakdown:</strong></p>
<ul>
<li><p>Defining classes: An individual class is defined with the <code>class</code> keyword followed by the class name.</p>
</li>
<li><p>Adding class properties: Class properties are added with a <code>+</code> sign. In the example above, <code>+breed</code> is a property.</p>
</li>
<li><p>Adding methods: Methods are recognized by mermaid using <code>()</code>, the round braces. Note that all the properties and methods are grouped under the same class using curly braces.</p>
</li>
<li><p>Defining return types: Return types are defined after the method name/ class name. <code>string</code> and <code>void</code> are the return types in the above code.</p>
</li>
<li><p>Defining relation ships: In OOP, relationships are the specific types of logical connections found on class and object diagrams. The following relationship types are supported in mermaid:</p>
</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Type</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td>&lt;</td><td>--</td><td>Inheritance</td></tr>
<tr>
<td>*--</td><td>Composition</td></tr>
<tr>
<td>o--</td><td>Aggregation</td></tr>
<tr>
<td>--&gt;</td><td>Association</td></tr>
<tr>
<td>--</td><td>Link (Solid)</td></tr>
<tr>
<td>..&gt;</td><td>Dependency</td></tr>
<tr>
<td>..</td><td>&gt;</td><td>Realization</td></tr>
<tr>
<td>..</td><td>Link (Dashed)</td></tr>
</tbody>
</table>
</div><p>Here is a quick implementation of inheritance:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173642098/8cac704a-455a-4317-93cc-885c4d28b066.png" alt="8cac704a-455a-4317-93cc-885c4d28b066" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Inheritance</em></p>
<h3 id="heading-how-to-create-a-gantt-chart"><strong>How to Create a Gantt Chart</strong></h3>
<p>A Gantt chart serves as a visual representation in the form of a bar chart. It effectively showcases a project's timeline, revealing the duration required for individual project components to reach completion.</p>
<p>You can render Gantt charts in Mermaid using this example:</p>
<pre><code class="lang-bash">```mermaid
gantt
    title Project Schedule
    dateFormat YYYY-MM-DD
    axisFormat %m/%d

    section Planning
    Define Project : 2023-01-01, 7d
    Research : 2023-01-08, 14d
    Define Requirements : 2023-01-22, 7d

    section Development
    Design : 2023-01-29, 21d
    Implementation : 2023-02-19, 28d

    section Testing
    Unit Testing : 2023-03-19, 14d
    Integration Testing : 2023-04-02, 14d

    section Deployment
    Deploy : 2023-04-16, 7d
    User Training : 2023-04-23, 14d

    section Maintenance
    Ongoing Support : 2023-05-07, 30d

```
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173699584/2755cdf2-a95e-40fa-a4ea-18eddd8d2919.png" alt="2755cdf2-a95e-40fa-a4ea-18eddd8d2919" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Gantt charts in mermaid</em></p>
<p><strong>Syntax breakdown:</strong></p>
<ul>
<li><p><code>gantt</code> specifies that you want to render a Gantt chart in mermaid.</p>
</li>
<li><p><code>title</code>represents the project title.</p>
</li>
<li><p><code>dateFormat YYYY-MM-DD</code> is the input date format for the chart.</p>
</li>
<li><p><code>axisFormat %m/%d</code> represents the shown date format, the output date, in the x-axis.</p>
</li>
<li><p><code>section</code> is used to separate different parts of the project.</p>
</li>
</ul>
<p>The x axis represents time and the y records the different tasks and the order in which they are to be completed.</p>
<h3 id="heading-how-to-create-a-pie-chart"><strong>How to Create a Pie Chart</strong></h3>
<p>A pie chart, also known as a circle chart, is a round visual representation used for displaying statistical data. It is divided into segments or slices to visually convey the numerical proportions of different categories or values.</p>
<p>Here is an example to create a pie chart in mermaid:</p>
<pre><code class="lang-bash">```mermaid
pie
    title Distribution of Expenses
    <span class="hljs-string">"Food"</span> : 60
    <span class="hljs-string">"Rent"</span> : 15
    <span class="hljs-string">"Entertainment"</span> : 10
    <span class="hljs-string">"Savings"</span> : 15

```
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732173761958/0664d574-0cc0-49d3-8744-68d1dbdd4d15.png" alt="0664d574-0cc0-49d3-8744-68d1dbdd4d15" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><em>Pie charts in mermaid</em></p>
<p><strong>Syntax breakdown:</strong></p>
<p>In this example:</p>
<ul>
<li><p><code>pie</code> indicates that we are creating a pie chart.</p>
</li>
<li><p><code>title</code> sets the title for the pie chart.</p>
</li>
<li><p>The items in double quotes represent the categories (e.g., "Food," "Rent," "Entertainment," "Savings").</p>
</li>
<li><p>The numbers after the colons represent the proportions or percentages for each category. In this case, "Food" occupies 60% of the chart, "Rent" 15%, "Entertainment" 10%, and "Savings" 15%.</p>
</li>
</ul>
<h2 id="heading-wrapping-up"><strong>Wrapping up</strong></h2>
<p>In this article, we just scratched the surface of rendering diagrams in Mermaid. The diagrams are highly customizable and allow you to create very complex diagrams as well.</p>
<p>Mermaid supports even more types of diagrams that are not mentioned in this tutorial. To learn more about Mermaid, check out their <a target="_blank" href="https://web.archive.org/web/20240526110100/http://mermaid.js.org/">official documentation</a>.</p>
<p>I hope you found this article helpful. I would love to connect with you on any of these <a target="_blank" href="https://web.archive.org/web/20240526110100/https://zaira_.bio.link/">platforms</a>.</p>
<p>See you in the next tutorial, happy coding 😁</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How I Got Accepted as an Author at freeCodeCamp ]]>
                </title>
                <description>
                    <![CDATA[ Life is full of surprises. Certain actions may lead to a chain of events and you find yourself in a completely different state.  One of my biggest achievements in 2021 was to get accepted as an author at freeCodeCamp. I have been writing articles on ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-i-got-accepted-as-an-author-at-freecodecamp/</link>
                <guid isPermaLink="false">66adea3cf928a14f7c42c353</guid>
                
                    <category>
                        <![CDATA[ freeCodeCamp.org ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technical writing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Tue, 01 Aug 2023 21:30:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/fcc-author-application.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Life is full of surprises. Certain actions may lead to a chain of events and you find yourself in a completely different state. </p>
<p>One of my biggest achievements in 2021 was to get accepted as an author at freeCodeCamp.</p>
<p>I have been writing articles on freeCodeCamp's community publication since September 2021 and have published 31 articles. I write mostly on Linux and occasionally on Python and Git. You can check out my author profile <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
<p>I have always enjoyed writing. I used to casually write stories or simply journaled about how my day went. But I never made any of my writings public. </p>
<p>I had been working as an application support admin for a few years. I learned a lot of interesting things during my routine work, and I loved making notes for myself. </p>
<p>I started to share them with my colleagues too, and realized they actually found them useful. I also noticed that people usually run away from documentation. But the drawback is that you may forget things very easily if the tech is complicated and there is a lot going on. </p>
<h2 id="heading-how-i-discovered-freecodecamp">How I Discovered freeCodeCamp</h2>
<p>It was a routine day at work when I was scrolling through LinkedIn. I saw that one of my colleagues had recently completed the Responsive Design Course on freeCodeCamp and had shared his certificate there. I congratulated him. </p>
<p>At the same time, I got curious about what freeCodeCamp was. At that time, I was also looking to polish my development skills.</p>
<p>I searched for freeCodeCamp online and followed them on Twitter. I had recently started using Twitter for learning about tech. Over there I saw that people were writing articles which freeCodeCamp was regularly sharing. </p>
<p>I explored some of the author profiles and the popular topics. I had always thought that in order to write a blog online, you had to be famous and have a huge social following. I also believed that the topic should be very complex and should be written about by an expert with years and years of experience. </p>
<p>I got even more curious and approached Abbey on Twitter. I asked how I could join as an author. That was the turning point. </p>
<p>She sent me the <a target="_blank" href="https://www.freecodecamp.org/news/developer-news-style-guide/">publication guide</a>, and I read it a couple of times. Then I decided to apply. There was a Google <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSdvbv9jd7hlgIsHZWJGfnldLo2hLdlputw3hJ42JWpv3ctL1w/viewform">form</a> with some questions. I shared some of my sample articles that I luckily had. At that time, I was writing as a guest author for a YouTuber's blog. </p>
<p>But...some time went by. I couldn't get a response.👀 To be honest, I was anxious.</p>
<p>I was eagerly waiting for an answer. Just before I was about to give up, I decided to check my spam folder. And there it was – the email that I had been waiting for!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-93-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-tips-to-help-you-get-accepted">Tips to Help You Get Accepted</h2>
<p>If you are keen about writing and showing it to the world, you should definitely apply for freeCodeCamp's author program. Here are some tips to strengthen your application.</p>
<ul>
<li>Have three writing samples ready – and show your best samples. You can publish some of your sample articles on open publishing platforms like <a target="_blank" href="https://hashnode.com/">Hashnode</a> and <a target="_blank" href="https://dev.to/">Dev.to</a> to get practice writing technical tutorials before applying to freeCodeCamp.</li>
<li>Don't think that you have to be an expert in every topic or you need to be a tech influencer to apply. Just make sure you do your research and present the information clearly with the primary goal of educating your readers.</li>
<li>There is no harm in applying again with better samples if you didn't qualify the first time. Your application would still be reviewed – just email Abbey or message her on Twitter to give her a heads up.</li>
</ul>
<p>Also, keep in mind that quality is always better than quantity. Here's a few additional tips related to that.</p>
<ul>
<li><strong>Plagiarism is never acceptable</strong>. So don't think you can get away with it. 👮‍♂️ If you're not sure what constitutes plagiarism, read up on it <strong>before you apply</strong>. If you think some of your articles contain plagiarism, write some more that don't. It's better for you, and everyone.</li>
<li>Be careful with using GPT. You can use it to assist you – help you create outlines, code samples (which you should test to make sure they work/run), and so on – and not to write the whole article for you. After all, your unique writing style is what makes you stand out. It's worth the extra time, plus you'll learn a whole lot more.</li>
</ul>
<h2 id="heading-what-did-i-get-in-return-as-an-author">What Did I Get in Return as an Author?</h2>
<p>The short answer is – meaningful connections!</p>
<p>The freeCodeCamp community is huge and powerful. I got many follows on my socials being on Twitter and LinkedIn (as freeCodeCamp shares many of the articles they publish on social media). </p>
<p>In the past 12 months, my articles have reached 1,904,450 people! I wasn't expecting to reach so many people when I was starting out.</p>
<p>I have also received appreciation from some of the kind readers. Some of my articles have also been featured in <a target="_blank" href="https://www.freecodecamp.org/news/quincy-larson-5-links-worth-your-time-email-full-list/">Quincy's weekly newsletter</a>.</p>

<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>If you have something you would like to share with the developer community, I would highly suggest you start writing. Whether you publish on your own blog, an open publishing site, or you apply and are accepted to freeCodeCamp's publication – I believe you'll see the benefits. You will also meet many great people along the way. 🤗 </p>
<p>BTW, I would be happy to connect with you on any of these <a target="_blank" href="https://zaira_.bio.link/">platforms</a>. 📧</p>
<p>Happy coding :D</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Faster HTML and CSS Code Using Emmet ]]>
                </title>
                <description>
                    <![CDATA[ Emmet is an essential development tool that helps you quickly create repetitive structures like lists, tables, or ordered elements with minimal typing. It is more like a shorthand that translates to multiple lines of HTML or a CSS attribute. Emmet is... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-faster-html-and-css-using-emmet/</link>
                <guid isPermaLink="false">66adea56007ea266ef6d9226</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 26 Jul 2023 14:24:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Copy-of-Copy-of-Copy-of-Copy-of-read-write-files-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Emmet is an essential development tool that helps you quickly create repetitive structures like lists, tables, or ordered elements with minimal typing. It is more like a shorthand that translates to multiple lines of HTML or a CSS attribute.</p>
<p>Emmet is built-in in many of the text editors like VS Code. However, you can also download it for your favorite text editor from <a target="_blank" href="https://emmet.io/download/">this</a> link. Emmet is also available inside some online IDEs like CodePen.</p>
<p>Look closely at the example below. See how easily we generated ten lines of code using only the keywords <code>ol&gt;li{This is a list}*10</code>?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Emmet doing its magic</em></p>
<p>We skipped copying and pasting ten lines and then counting to see if there were ten items. Doing this manually also introduces a chance of human error.</p>
<p>In this tutorial, we will learn some Emmet shortcuts that generate HTML and CSS quickly.</p>
<h2 id="heading-emmet-shortcuts-for-html">Emmet Shortcuts for HTML</h2>
<h3 id="heading-how-to-create-comments">How to Create Comments</h3>
<p>To comment a single line, press <code>Ctrl + /</code>.</p>
<p>To comment multiple lines, select them and then press <code>Ctrl + /</code>.</p>
<h3 id="heading-multiplication-in-emmet">Multiplication in Emmet</h3>
<p>You can create multiple elements by specifying the count after <code>*</code>. </p>
<p>For example, <code>p*10</code> would generate 10 <code>p</code> elements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-s.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Create any number of elements using multiplication</em></p>
<h3 id="heading-how-to-create-direct-children">How to Create Direct children</h3>
<p>You can create direct children using the <code>&gt;</code> symbol.</p>
<p><code>ol&gt;li</code> would create an <code>li</code> inside the <code>ol</code> element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-o.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Creating direct children</em></p>
<h3 id="heading-how-to-create-siblings">How to Create Siblings</h3>
<p>You can create siblings using the<code>+</code> symbol.</p>
<p><code>div+p</code> would create a <code>div</code> element and a <code>p</code> element on the same level.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-xx.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Creating siblings</em></p>
<h3 id="heading-how-to-combine-selectors">How to Combine selectors</h3>
<p>You can combine the sibling and the child selector to create a structure. For example <code>div+p&gt;span</code> would result in a <code>div</code> and a <code>p</code> element on the same level with a <code>span</code> element as a child of <code>p</code> selector:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-ss.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Combining selectors</em></p>
<h3 id="heading-how-to-code-complex-structures-using-brackets">How to code complex structures using brackets <code>()</code></h3>
<p>Brackets <code>()</code> can be used to separate different parts of the structure. </p>
<p>By using the Emmet shortcut <code>(main&gt;div)+div&gt;ul&gt;li*5</code>, you can create the following complex structure:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-ds.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Creating complex structures</em></p>
<h3 id="heading-how-to-use-emmet-for-setting-ids">How to use Emmet for setting IDs</h3>
<p>If you want to create a <code>p</code> element with the ID of <code>news-section</code>, you can do so using this Emmet: <code>p#news-section</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-vv.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Emmet for setting IDs</em></p>
<h3 id="heading-how-to-use-emmet-for-setting-classes">How to use Emmet for setting Classes</h3>
<p>If you want to create a <code>p</code> element with the class of <code>news-espanol</code>, you can do so using this Emmet: <code>p.news-espanol</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-ll.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Emmet for setting Classes</em></p>
<h3 id="heading-how-to-create-attributes">How to create Attributes</h3>
<p>It is possible to create elements with certain attributes using Emmet.</p>
<p>The Emmet shortcut <code>button[type=submit]</code> would create this button element: <code>&lt;button type="submit"&gt;&lt;/button&gt;</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-bb.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Emmet for setting attributes</em></p>
<h3 id="heading-how-to-add-content-to-elements">How to add Content to Elements</h3>
<p>It is fairly easy to provide content for your elements using Emmets. </p>
<p><code>p{This is a paragraph}</code> would create a <code>p</code> element with content "This is a paragraph".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-pp.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Emmet for setting content</em></p>
<h3 id="heading-enumeration">Enumeration</h3>
<p>In Emmet, enumeration typically refers to the process of generating multiple HTML elements with sequential numbers or alphabets.   </p>
<p>Here is an example of enumeration: <code>ul&gt;li*5{List item number $}</code>.</p>
<p>The <code>$</code> signifies the point where enumeration starts. The <code>*5</code> means to repeat this structure five times, with the numbers incrementing for each iteration.</p>
<p>Let's see this in action:  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-pj.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-generate-lorem-ipsum-text">How to generate Lorem Ipsum text</h3>
<p>You don't need to Google for "Lorem ipsum" text if you are using Emmet.</p>
<p><code>Lorem20</code> would generate a text of 20 characters.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-xxx.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Generate lorem text using Emmet</em></p>
<h3 id="heading-how-to-link-css">How to Link CSS</h3>
<p>To link a CSS file, type <code>link</code> and press enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-gg.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Link external CSS</em></p>
<h3 id="heading-how-to-link-javascript">How to Link JavaScript</h3>
<p>To link JavaScript, use the Emmet shortcut <code>script:src</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/emmet-jjj.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Link JavaScript</em></p>
<h2 id="heading-emmet-shortcuts-for-css">Emmet Shortcuts for CSS</h2>
<p>Just like HTML, Emmet is also available for CSS.</p>
<p>Here are the Emmet shortcuts for some of the commonly used properties:</p>
<ul>
<li><code>m10</code> → <code>margin: 10px;</code></li>
<li><code>p-10</code> → <code>padding: -10px;</code>    </li>
<li><code>m20p</code> →  <code>margin: 20%;</code>  </li>
<li><code>w100p</code> → <code>width: 100%;</code></li>
<li><code>bgc#ff</code> → <code>background-color: #fff</code></li>
<li><code>db</code> → <code>display: block;</code></li>
<li><code>dib</code>  → <code>display: inline-block;</code></li>
<li><code>df</code>  → <code>display: flex;</code></li>
<li><code>tac</code> → <code>text-align: center;</code></li>
<li><code>tar</code> → <code>text-align: right;</code></li>
<li><code>c</code>  → <code>color: #000;</code></li>
<li><code>o</code>  → <code>overflow: hidden;</code></li>
<li><code>z</code> →  <code>z-index: 1;</code></li>
</ul>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>If you are into development, I highly recommend learning Emmet.</p>
<p>You will spend less time writing code and get much faster results.</p>
<p>I bet that once you start using it, your development experience will upgrade to a whole new level!</p>
<p>What’s your favorite thing you learned from this tutorial? You can also connect with me on any of these <a target="_blank" href="https://zaira_.bio.link/">platforms</a>. 📧</p>
<p>See you in the next tutorial, happy coding 😁</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Linux on a Windows Machine – 5 Different Approaches ]]>
                </title>
                <description>
                    <![CDATA[ As a developer, you might need to run both Linux and Windows side by side. Luckily, there are a number of ways you can get the best of both worlds without getting different computers for each operating system.  In this article, we'll explore a few wa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/5-ways-to-use-linux-on-a-windows-machine/</link>
                <guid isPermaLink="false">66adea1ec537123a64ede7f8</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WSL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Fri, 09 Jun 2023 15:03:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/5-ways-to-use-Linux-on-a-Windows-machine.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a developer, you might need to run both Linux and Windows side by side. Luckily, there are a number of ways you can get the best of both worlds without getting different computers for each operating system. </p>
<p>In this article, we'll explore a few ways to use Linux on a Windows machine. Some of them are browser-based or cloud-based that do not need any installation prior to using them.</p>
<p>Here are the methods we'll be discussing:</p>
<ul>
<li>Dual boot</li>
<li>Windows Subsystem for Linux (WSL)</li>
<li>Virtual Machines (VM)</li>
<li>Browser-based solutions</li>
<li>Cloud-based solutions</li>
</ul>
<h2 id="heading-option-1-dual-boot-linux-windows">Option 1: "Dual-boot" Linux + Windows</h2>
<p>With dual boot, you can install Linux alongside Windows on your computer, allowing you to choose which operating system to use at startup. </p>
<p>This requires partitioning your hard drive and installing Linux on a separate partition. With this approach, you can only use one operating system at a time.</p>
<p>If this sounds like the way you want to go, <a target="_blank" href="https://www.freecodecamp.org/news/how-to-dual-boot-windows-10-and-ubuntu-linux-dual-booting-tutorial/">here is a useful tutorial</a> on setting up dual boot on Windows 10.</p>
<h2 id="heading-option-2-use-windows-subsystem-for-linux-wsl">Option 2: Use Windows Subsystem for Linux (WSL)</h2>
<p>Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.</p>
<p>Using WSL has some advantages:</p>
<ul>
<li>The setup for WSL is simple and not time consuming.</li>
<li>It is lightweight compared to VMs where you have to allocate resources from the host machine.</li>
<li>You don't need to install any ISO or virtual disc image for Linux machines which tend to be heavy files.</li>
<li>You can use Windows and Linux side by side.</li>
</ul>
<p>If this sounds like the right option for you, <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-wsl2-windows-subsystem-for-linux-2-on-windows-10/">here is a detailed guide</a> on how to install and use WSL.</p>
<h2 id="heading-option-3-use-a-virtual-machine-vm">Option 3: Use a Virtual Machine (VM)</h2>
<p>A virtual machine (VM) is a software emulation of a physical computer system. It allows you to run multiple operating systems and applications on a single physical machine simultaneously. Here's a detailed explanation of VMs:</p>
<p>You can use virtualization software such as Oracle VirtualBox or VMware to create a virtual machine running Linux within your Windows environment. This allows you to run Linux as a guest operating system alongside Windows.</p>
<p>VM software provides options to allocate and manage hardware resources for each VM, including CPU cores, memory, disk space, and network bandwidth. You can adjust these allocations based on the requirements of the guest operating systems and applications.</p>
<p>Here are some of the options available for virtualization:</p>
<ul>
<li><a target="_blank" href="https://www.virtualbox.org/">Oracle virtual box</a></li>
<li><a target="_blank" href="https://multipass.run/">Multipass</a></li>
<li><a target="_blank" href="https://www.vmware.com/content/vmware/vmware-published-sites/us/products/workstation-player.html.html">VMware workstation player</a></li>
</ul>
<h2 id="heading-option-4-use-a-browser-based-solution">Option 4: Use a Browser-based Solution</h2>
<p>Browser based solutions are particularly useful for quick testing, learning, or accessing Linux environments from devices that don't have Linux installed.</p>
<p>You can either use online code editors or web based terminals to access Linux. Note that you usually don't have full administration privileges in these cases. </p>
<h3 id="heading-online-code-editors">Online code editors</h3>
<p>Online code editors offer editors with built-in Linux terminals. While their primary purpose is coding, you can also utilize the Linux terminal to execute commands and perform tasks.</p>
<p><a target="_blank" href="https://replit.com/">Replit</a> is an example of an online code editor, where you can write your code and access the Linux shell at the same time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/replit.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Replit provides a code editor and a Linux shell.</em></p>
<h3 id="heading-web-based-linux-terminals">Web-based Linux terminals</h3>
<p>Online Linux terminals allow you to access a Linux command-line interface directly from your browser. These terminals provide a web-based interface to a Linux shell, enabling you to execute commands and work with Linux utilities. </p>
<p>One such example is <a target="_blank" href="https://jslinux.org/">JSLinux</a>. The screenshot below shows a ready to use Linux environment:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/jslinux.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Accessing Linux via JSLinux</em></p>
<h2 id="heading-option-5-use-a-cloud-based-solution">Option 5: Use a Cloud-based Solution</h2>
<p>Instead of running Linux directly on your Windows machine, you can consider using cloud-based Linux environments or virtual private servers (VPS) to access and work with Linux remotely. </p>
<p>Services like Amazon EC2, Microsoft Azure, or DigitalOcean provide Linux instances that you can connect to from your Windows computer. Note that some of these services offer free tiers, but they are not usually free in the long run.</p>
<h2 id="heading-how-to-choose-the-correct-method">How to Choose the Correct Method</h2>
<p>The choice is totally dependent on your use case. But there are some factors that may help you decide which option works the best for you. Let's discuss them:</p>
<ul>
<li>Access level/elevated privilege: If you require full administrative privileges, it is better to skip the browser-based solutions. WSL, dual booting, VMs, and cloud-based solutions provide you with full administrative control.</li>
<li>Cost: Cloud-based solutions offer services against a subscription fee. This cost varies depending on the choice of operating system, hardware specs of the machine, traffic, and so on. If you are on a tight budget, cloud-based solutions might not be the best.</li>
<li>Scalability: If you are just starting, but plan to do resource exhaustive development in the future, you can always scale up the physical specs of your machine. Some options that support upgrading are cloud-based solutions and VMs. You can add more processors or increase the RAM as per your needs.</li>
<li>Current system's hardware specs: If your current system has lower RAM and storage, running VMs can make the system heavy. It would be better to opt for cloud-based or browser based solutions.</li>
<li>Switching: If you don't plan to use Windows and Linux side by side, dual-boot can be a really good option. It offers a complete and focused Linux experience.</li>
</ul>
<h2 id="heading-my-setup">My Setup</h2>
<p>I am using Ubuntu VM installed through VMWare workstation player. It is doing a great job as I can frequently switch between two operating systems. It was also simple to setup and I can enjoy the admin privileges as well!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/my-set.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>I hope you found this article helpful. What’s your favorite thing you learned from this tutorial? I would love to connect with you on any of these <a target="_blank" href="https://zaira_.bio.link/">platforms</a>. 📧</p>
<p>See you in the next tutorial, happy coding 😁</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Bash Scripting Tutorial – Linux Shell Script and Command Line for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In Linux, process automation relies heavily on shell scripting. This involves creating a file containing a series of commands that can be executed together. In this article, we'll start with the basics of bash scripting which includes variables, comm... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/bash-scripting-tutorial-linux-shell-script-and-command-line-for-beginners/</link>
                <guid isPermaLink="false">66adea246778e7bd69427bbc</guid>
                
                    <category>
                        <![CDATA[ Bash ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ shell script ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Mon, 20 Mar 2023 17:35:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Copy-of-Cast-a-Function-in-SQL---Convert-Char-to-Int-SQL-Server-Example.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Linux, process automation relies heavily on shell scripting. This involves creating a file containing a series of commands that can be executed together.</p>
<p>In this article, we'll start with the basics of bash scripting which includes variables, commands, inputs/ outputs, and debugging. We'll also see examples of each along the way.</p>
<p>Let's get started. 🚀</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-pre-requisites">Pre-requisites</a></li>
<li><a class="post-section-overview" href="#heading-introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#heading-definition-of-bash-scripting">Definition of Bash scripting</a></li>
<li><a class="post-section-overview" href="#heading-advantages-of-bash-scripting">Advantages of Bash scripting</a></li>
<li><a class="post-section-overview" href="#heading-overview-of-bash-shell-and-command-line-interface">Overview of Bash shell and command line interface</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-started-with-bash-scripting">How to Get Started with Bash Scripting</a></li>
<li><a class="post-section-overview" href="#how-to-run-bash-commands-from-the-command-line">How to Run Bash Commands from the Command Line</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-and-execute-bash-scripts">How to Create and Execute Bash Scripts</a></li>
<li><p><a class="post-section-overview" href="#heading-bash-scripting-basics">Bash Scripting Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-comments-in-bash-scripting">Comments in bash scripting</a></p>
</li>
<li><a class="post-section-overview" href="#heading-variables-and-data-types-in-bash">Variables and data types in Bash</a></li>
<li><a class="post-section-overview" href="#heading-input-and-output-in-bash-scripts">Input and output in Bash scripts</a></li>
<li><a class="post-section-overview" href="#heading-basic-bash-commands-echo-read-etc">Basic Bash commands (echo, read, etc.)</a></li>
<li><p><a class="post-section-overview" href="#heading-conditional-statements-ifelse">Conditional statements (if/else)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-looping-and-branching-in-bash">Looping and Branching in Bash</a></p>
</li>
<li><a class="post-section-overview" href="#heading-while-loop">While loop</a></li>
<li><a class="post-section-overview" href="#heading-for-loop">For loop</a></li>
<li><a class="post-section-overview" href="#heading-case-statements">Case statements</a></li>
<li><a class="post-section-overview" href="#heading-how-to-schedule-scripts-using-cron">How to Schedule Scripts using cron</a></li>
<li><a class="post-section-overview" href="#heading-how-to-debug-and-troubleshoot-bash-scripts">How to Debug and Troubleshoot Bash Scripts</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
<li><a class="post-section-overview" href="#heading-resources-for-learning-more-about-bash-scripting">Resources for learning more about Bash scripting</a></li>
</ol>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<p>To follow along with this tutorial, you should have the following accesses:</p>
<ul>
<li>A running version of Linux with access to the command line.</li>
</ul>
<p>If you do not have Linux installed or you are just starting out, you can easily access the Linux command line through <a target="_blank" href="https://replit.com/~">Replit</a>. Replit is a browser-based IDE where you can access the bash shell in a few minutes.</p>
<p>You can also install Linux on top of your Windows system using WSL (Windows Subsystem for Linux). <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-wsl2-windows-subsystem-for-linux-2-on-windows-10/">Here</a> is a tutorial for that.</p>
<h2 id="heading-introduction">Introduction</h2>
<h3 id="heading-definition-of-bash-scripting">Definition of Bash scripting</h3>
<p>A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line. </p>
<p>By saving these commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.</p>
<h3 id="heading-advantages-of-bash-scripting">Advantages of Bash scripting</h3>
<p>Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems. Some advantages of shell scripting are:</p>
<ul>
<li><strong>Automation</strong>: Shell scripts allow you to automate repetitive tasks and processes, saving time and reducing the risk of errors that can occur with manual execution.</li>
<li><strong>Portability</strong>: Shell scripts can be run on various platforms and operating systems, including Unix, Linux, macOS, and even Windows through the use of emulators or virtual machines.</li>
<li><strong>Flexibility</strong>: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.</li>
<li><strong>Accessibility</strong>: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.</li>
<li><strong>Integration</strong>: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.</li>
<li><strong>Debugging</strong>: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.</li>
</ul>
<h3 id="heading-overview-of-bash-shell-and-command-line-interface">Overview of Bash shell and command line interface</h3>
<p>The terms "shell" and "bash" are used interchangeably. But there is a subtle difference between the two. </p>
<p>The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.</p>
<p>A shell or command-line interface looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-135.png" alt="Image" width="600" height="400" loading="lazy">
<em>The shell accepts commands from the user and displays the output</em></p>
<p>In the above output, <code>zaira@Zaira</code> is the shell prompt. When a shell is used interactively, it displays a <code>$</code> when it is waiting for a command from the user. </p>
<p>If the shell is running as root (a user with administrative rights), the prompt is changed to <code>#</code>. The superuser shell prompt looks like this:</p>
<pre><code class="lang-bash">[root@host ~]<span class="hljs-comment">#</span>
</code></pre>
<p>Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.</p>
<p>You can determine your shell type using the <code>ps</code> command:</p>
<pre><code class="lang-bash">ps
</code></pre>
<p>Here is the output for me:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-134.png" alt="Image" width="600" height="400" loading="lazy">
<em>Checking the shell type. I'm using bash shell</em></p>
<p>In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.</p>
<p>Note: In this tutorial, we will be using the "bash" shell.</p>
<h2 id="heading-how-to-get-started-with-bash-scripting">How to Get Started with Bash Scripting</h2>
<h3 id="heading-running-bash-commands-from-the-command-line">Running Bash commands from the command line</h3>
<p>As mentioned earlier, the shell prompt looks something like this:</p>
<pre><code class="lang-bash">[username@host ~]$
</code></pre>
<p>You can enter any command after the <code>$</code> sign and see the output on the terminal.</p>
<p>Generally, commands follow this syntax:</p>
<pre><code>command [OPTIONS] <span class="hljs-built_in">arguments</span>
</code></pre><p>Let's discuss a few basic bash commands and see their outputs. Make sure to follow along :) </p>
<ul>
<li><code>date</code>: Displays the current date</li>
</ul>
<pre><code class="lang-bash">zaira@Zaira:~/shell-tutorial$ date
Tue Mar 14 13:08:57 PKT 2023
</code></pre>
<ul>
<li><code>pwd</code>: Displays the present working directory.</li>
</ul>
<pre><code class="lang-bash">zaira@Zaira:~/shell-tutorial$ <span class="hljs-built_in">pwd</span>
/home/zaira/shell-tutorial
</code></pre>
<ul>
<li><code>ls</code>: Lists the contents of the current directory.</li>
</ul>
<pre><code class="lang-bash">zaira@Zaira:~/shell-tutorial$ ls
check_plaindrome.sh  count_odd.sh  env  <span class="hljs-built_in">log</span>  temp
</code></pre>
<ul>
<li><code>echo</code>: Prints a string of text, or value of a variable to the terminal.</li>
</ul>
<pre><code class="lang-bash">zaira@Zaira:~/shell-tutorial$ <span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello bash"</span>
Hello bash
</code></pre>
<p>You can always refer to a commands manual with the <code>man</code> command.</p>
<p>For example, the manual for <code>ls</code> looks something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-138.png" alt="Image" width="600" height="400" loading="lazy">
<em>You can see options for a command in detail using <code>man</code></em></p>
<h3 id="heading-how-to-create-and-execute-bash-scripts">How to Create and Execute Bash scripts</h3>
<h4 id="heading-script-naming-conventions">Script naming conventions</h4>
<p>By naming convention, bash scripts end with <code>.sh</code>. However, bash scripts can run perfectly fine without the <code>sh</code> extension.</p>
<h4 id="heading-adding-the-shebang">Adding the Shebang</h4>
<p>Bash scripts start with a <code>shebang</code>. Shebang is a combination of <code>bash #</code> and <code>bang !</code> followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.</p>
<p>Below is an example of the shebang statement.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
</code></pre>
<p>You can find your bash shell path (which may vary from the above) using the command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">which</span> bash
</code></pre>
<h4 id="heading-creating-our-first-bash-script">Creating our first bash script</h4>
<p>Our first script prompts the user to enter a path. In return, its contents will be listed. </p>
<p>Create a file named <code>run_all.sh</code> using the <code>vi</code> command. You can use any editor of your choice. </p>
<pre><code class="lang-bash">vi run_all.sh
</code></pre>
<p>Add the following commands in your file and save it:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
<span class="hljs-built_in">read</span> the_path

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
ls <span class="hljs-variable">$the_path</span>
</code></pre>
<p>Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.  </p>
<pre><code class="lang-bash">  1 <span class="hljs-comment">#!/bin/bash</span>
  2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`
  3
  4 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
  5 <span class="hljs-built_in">read</span> the_path
  6
  7 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
  8 ls <span class="hljs-variable">$the_path</span>
</code></pre>
<ul>
<li>Line #1: The shebang (<code>#!/bin/bash</code>) points toward the bash shell path.</li>
<li>Line #2: The <code>echo</code> command is displaying the current date and time on the terminal. Note that the <code>date</code> is in backticks.</li>
<li>Line #4: We want the user to enter a valid path. </li>
<li>Line #5: The <code>read</code> command reads the input and stores it in the variable <code>the_path</code>.</li>
<li>line #8: The <code>ls</code> command takes the variable with the stored path and displays the current files and folders.</li>
</ul>
<h4 id="heading-executing-the-bash-script">Executing the bash script</h4>
<p>To make the script executable, assign execution rights to your user using this command:</p>
<pre><code class="lang-bash">chmod u+x run_all.sh
</code></pre>
<p>Here,</p>
<ul>
<li><code>chmod</code> modifies the ownership of a file for the current user :<code>u</code>.</li>
<li><code>+x</code> adds the execution rights to the current user. This means that the user who is the owner can now run the script.</li>
<li><code>run_all.sh</code> is the file we wish to run.</li>
</ul>
<p>You can run the script using any of the mentioned methods:</p>
<ul>
<li><code>sh run_all.sh</code></li>
<li><code>bash run_all.sh</code></li>
<li><code>./run_all.sh</code></li>
</ul>
<p>Let's see it running in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/run-script-bash-2.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-bash-scripting-basics">Bash Scripting Basics</h2>
<h3 id="heading-comments-in-bash-scripting">Comments in bash scripting</h3>
<p>Comments start with a <code>#</code> in bash scripting. This means that any line that begins with a <code>#</code> is a comment and will be ignored by the interpreter. </p>
<p>Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code. </p>
<p>These are examples of comments:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># This is an example comment</span>
<span class="hljs-comment"># Both of these lines will be ignored by the interpreter</span>
</code></pre>
<h3 id="heading-variables-and-data-types-in-bash">Variables and data types in Bash</h3>
<p>Variables let you store data. You can use variables to read, access, and manipulate data throughout your script. </p>
<p>There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.</p>
<p>In Bash, you can use and set the variable values in the following ways:</p>
<ol>
<li>Assign the value directly:</li>
</ol>
<pre><code class="lang-bash">country=Pakistan
</code></pre>
<ol start="2">
<li>Assign the value based on the output obtained from a program or command, using command substitution. Note that <code>$</code> is required to access an existing variable's value.</li>
</ol>
<pre><code class="lang-bash">same_country=<span class="hljs-variable">$country</span>
</code></pre>
<p>To access the variable value, append <code>$</code> to the variable name.</p>
<pre><code class="lang-bash">zaira@Zaira:~$ country=Pakistan
zaira@Zaira:~$ <span class="hljs-built_in">echo</span> <span class="hljs-variable">$country</span>
Pakistan
zaira@Zaira:~$ new_country=<span class="hljs-variable">$country</span>
zaira@Zaira:~$ <span class="hljs-built_in">echo</span> <span class="hljs-variable">$new_country</span>
Pakistan
</code></pre>
<h3 id="heading-variable-naming-conventions">Variable naming conventions</h3>
<p>In Bash scripting, the following are the variable naming conventions:</p>
<ol>
<li>Variable names should start with a letter or an underscore (<code>_</code>).</li>
<li>Variable names can contain letters, numbers, and underscores (<code>_</code>).</li>
<li>Variable names are case-sensitive.</li>
<li>Variable names should not contain spaces or special characters.</li>
<li>Use descriptive names that reflect the purpose of the variable.</li>
<li>Avoid using reserved keywords, such as <code>if</code>, <code>then</code>, <code>else</code>, <code>fi</code>, and so on as variable names.</li>
</ol>
<p>Here are some examples of valid variable names in Bash:</p>
<pre><code class="lang-bash">name
count
_var
myVar
MY_VAR
</code></pre>
<p>And here are some examples of invalid variable names:</p>
<pre><code class="lang-bash">2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)
</code></pre>
<p>Following these naming conventions helps make Bash scripts more readable and easier to maintain.</p>
<h3 id="heading-input-and-output-in-bash-scripts">Input and output in Bash scripts</h3>
<h4 id="heading-gathering-input">Gathering input</h4>
<p>In this section, we'll discuss some methods to provide input to our scripts. </p>
<ol>
<li>Reading the user input and storing it in a variable</li>
</ol>
<p>We can read the user input using the <code>read</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash </span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"What's your name?"</span> 

<span class="hljs-built_in">read</span> entered_name 

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nWelcome to bash tutorial"</span> <span class="hljs-variable">$entered_name</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<ol start="2">
<li>Reading from a file</li>
</ol>
<p>This code reads each line from a file named <code>input.txt</code> and prints it to the terminal. We'll study while loops later in this article.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> <span class="hljs-built_in">read</span> line
<span class="hljs-keyword">do</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-variable">$line</span>
<span class="hljs-keyword">done</span> &lt; input.txt
</code></pre>
<ol start="3">
<li>Command line arguments</li>
</ol>
<p>In a bash script or function, <code>$1</code> denotes the initial argument passed, <code>$2</code> denotes the second argument passed, and so forth.</p>
<p>This script takes a name as a command-line argument and prints a personalized greeting.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$1</span>!"</span>
</code></pre>
<p>We have supplied <code>Zaira</code> as our argument to the script.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$1</span>!"</span>
</code></pre>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h4 id="heading-displaying-output">Displaying output</h4>
<p>Here we'll discuss some methods to receive output from the scripts.</p>
<ol>
<li>Printing to the terminal:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, World!"</span>
</code></pre>
<p>This prints the text "Hello, World!" to the terminal.</p>
<ol start="2">
<li>Writing to a file:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"This is some text."</span> &gt; output.txt
</code></pre>
<p>This writes the text "This is some text." to a file named <code>output.txt</code>. Note that the <code>&gt;</code>operator overwrites a file if it already has some content. </p>
<ol start="3">
<li>Appending to a file:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"More text."</span> &gt;&gt; output.txt
</code></pre>
<p>This appends the text "More text." to the end of the file <code>output.txt</code>.</p>
<ol start="4">
<li>Redirecting output:</li>
</ol>
<pre><code class="lang-bash">ls &gt; files.txt
</code></pre>
<p>This lists the files in the current directory and writes the output to a file named <code>files.txt</code>. You can redirect output of any command to a file this way.</p>
<h3 id="heading-basic-bash-commands-echo-read-etc">Basic Bash commands (echo, read, etc.)</h3>
<p>Here is a list of some of the most commonly used bash commands:</p>
<ol>
<li><code>cd</code>: Change the directory to a different location.</li>
<li><code>ls</code>: List the contents of the current directory.</li>
<li><code>mkdir</code>: Create a new directory.</li>
<li><code>touch</code>: Create a new file.</li>
<li><code>rm</code>: Remove a file or directory.</li>
<li><code>cp</code>: Copy a file or directory.</li>
<li><code>mv</code>: Move or rename a file or directory.</li>
<li><code>echo</code>: Print text to the terminal.</li>
<li><code>cat</code>: Concatenate and print the contents of a file.</li>
<li><code>grep</code>: Search for a pattern in a file.</li>
<li><code>chmod</code>: Change the permissions of a file or directory.</li>
<li><code>sudo</code>: Run a command with administrative privileges.</li>
<li><code>df</code>: Display the amount of disk space available.</li>
<li><code>history</code>: Show a list of previously executed commands.</li>
<li><code>ps</code>: Display information about running processes.</li>
</ol>
<h3 id="heading-conditional-statements-ifelse">Conditional statements (if/else)</h3>
<p>Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including <code>if</code>, <code>if-else</code>, <code>if-elif-else</code>, and nested conditionals.</p>
<p><strong>Syntax</strong>:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [[ condition ]];
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">elif</span> [[ condition ]]; <span class="hljs-keyword">then</span>
    statement 
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<p>We can use logical operators such as AND <code>-a</code> and OR <code>-o</code> to make comparisons that have more significance. </p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -gt 60 -a <span class="hljs-variable">$b</span> -lt 100 ]
</code></pre>
<p>Let's see an example of a Bash script that uses <code>if</code>, <code>if-else</code>, and <code>if-elif-else</code> statements to determine if a user-inputted number is positive, negative, or zero:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Please enter a number: "</span>
<span class="hljs-built_in">read</span> num

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$num</span> -gt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is positive"</span>
<span class="hljs-keyword">elif</span> [ <span class="hljs-variable">$num</span> -lt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is negative"</span>
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is zero"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p>The script first prompts the user to enter a number. Then, it uses an <code>if</code> statement to check if the number is greater than 0. If it is, the script outputs that the number is positive. If the number is not greater than 0, the script moves on to the next statement, which is an <code>if-elif</code> statement. Here, the script checks if the number is less than 0. If it is, the script outputs that the number is negative. Finally, if the number is neither greater than 0 nor less than 0, the script uses an <code>else</code> statement to output that the number is zero.</p>
<p>Seeing it in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/test-odd.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-looping-and-branching-in-bash">Looping and Branching in Bash</h2>
<h3 id="heading-while-loop">While loop</h3>
<p>While loops check for a condition and loop until the condition remains <code>true</code>. We need to provide a counter statement that increments the counter to control loop execution.</p>
<p>In the example below, <code>(( i += 1 ))</code> is the counter statement that increments the value of <code>i</code>. The loop will run exactly 10 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
i=1
<span class="hljs-keyword">while</span> [[ <span class="hljs-variable">$i</span> -le 10 ]] ; <span class="hljs-keyword">do</span>
   <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$i</span>"</span>
  (( i += 1 ))
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-187.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-for-loop">For loop</h3>
<p>The <code>for</code> loop, just like the <code>while</code> loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.</p>
<p>In the example below, the loop will iterate 5 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> {1..5}
<span class="hljs-keyword">do</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$i</span>
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-186.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-case-statements">Case statements</h3>
<p>In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">case</span> expression <span class="hljs-keyword">in</span>
    pattern1)
        <span class="hljs-comment"># code to execute if expression matches pattern1</span>
        ;;
    pattern2)
        <span class="hljs-comment"># code to execute if expression matches pattern2</span>
        ;;
    pattern3)
        <span class="hljs-comment"># code to execute if expression matches pattern3</span>
        ;;
    *)
        <span class="hljs-comment"># code to execute if none of the above patterns match expression</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against. </p>
<p>The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.</p>
<p>Let's see an example.</p>
<pre><code class="lang-bash">fruit=<span class="hljs-string">"apple"</span>

<span class="hljs-keyword">case</span> <span class="hljs-variable">$fruit</span> <span class="hljs-keyword">in</span>
    <span class="hljs-string">"apple"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a red fruit."</span>
        ;;
    <span class="hljs-string">"banana"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a yellow fruit."</span>
        ;;
    <span class="hljs-string">"orange"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is an orange fruit."</span>
        ;;
    *)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Unknown fruit."</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>In this example, since the value of "fruit" is "apple", the first pattern matches, and the block of code that echoes "This is a red fruit." is executed. If the value of "fruit" were instead "banana", the second pattern would match and the block of code that echoes "This is a yellow fruit." would execute, and so on. If the value of "fruit" does not match any of the specified patterns, the default case is executed, which echoes "Unknown fruit."</p>
<h2 id="heading-how-to-schedule-scripts-using-cron">How to Schedule Scripts using cron</h2>
<p>Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or specific time basis. The automation capabilities provided by cron play a crucial role in Linux system administration.</p>
<p>Below is the syntax to schedule crons:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Cron job example</span>
* * * * * sh /path/to/script.sh
</code></pre>
<p>Here, the <code>*</code>s represent minute(s) hour(s) day(s) month(s) weekday(s), respectively.</p>
<p>Below are some examples of scheduling cron jobs.</p>
<table>
<thead>
<tr>
<th>Schedule</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>0 0 <em> </em> <em></em></code></td>
<td>Run a script at midnight every day</td>
<td><code>0 0  <em> </em> /path/to/script.sh</code></td>
</tr>
<tr>
<td><code><em>/5 </em> <em> </em> <em></em></code></td>
<td>Run a script every 5 minutes</td>
<td><code>/5 <em> </em> <em> </em> /path/to/script.sh</code></td>
</tr>
<tr>
<td><code>0 6 <em> </em> 1-5</code></td>
<td>Run a script at 6 am from Monday to Friday</td>
<td><code>0 6 <em> </em> 1-5 /path/to/script.sh</code></td>
</tr>
<tr>
<td><code>0 0 1-7 <em> </em></code></td>
<td>Run a script on the first 7 days of every month</td>
<td><code>0 0 1-7 <em> </em> /path/to/script.sh</code></td>
</tr>
<tr>
<td><code>0 12 1 <em> </em></code></td>
<td>Run a script on the first day of every month at noon</td>
<td><code>0 12 1 <em> </em> /path/to/script.sh</code></td>
</tr>
</tbody>
</table>

<h4 id="heading-using-crontab">Using crontab</h4>
<p>The <code>crontab</code> utility is used to add and edit the cron jobs.</p>
<p><code>crontab -l</code> lists the already scheduled scripts for a particular user.</p>
<p>You can add and edit the cron through <code>crontab -e</code>.</p>
<p>You can read more about corn jobs in my <a target="_blank" href="https://www.freecodecamp.org/news/cron-jobs-in-linux/">other article here</a>. </p>
<h2 id="heading-how-to-debug-and-troubleshoot-bash-scripts">How to Debug and Troubleshoot Bash Scripts</h2>
<p>Debugging and troubleshooting are essential skills for any Bash scripter. While Bash scripts can be incredibly powerful, they can also be prone to errors and unexpected behavior. In this section, we will discuss some tips and techniques for debugging and troubleshooting Bash scripts.</p>
<h3 id="heading-set-the-set-x-option">Set the <code>set -x</code> option</h3>
<p>One of the most useful techniques for debugging Bash scripts is to set the <code>set -x</code> option at the beginning of the script. This option enables debugging mode, which causes Bash to print each command that it executes to the terminal, preceded by a <code>+</code> sign. This can be incredibly helpful in identifying where errors are occurring in your script.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">set</span> -x

<span class="hljs-comment"># Your script goes here</span>
</code></pre>
<h3 id="heading-check-the-exit-code">Check the exit code</h3>
<p>When Bash encounters an error, it sets an exit code that indicates the nature of the error. You can check the exit code of the most recent command using the <code>$?</code> variable. A value of <code>0</code> indicates success, while any other value indicates an error.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Your script goes here</span>

<span class="hljs-keyword">if</span> [ $? -ne 0 ]; <span class="hljs-keyword">then</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"Error occurred."</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<h3 id="heading-use-echo-statements">Use <code>echo</code> statements</h3>
<p>Another useful technique for debugging Bash scripts is to insert <code>echo</code> statements throughout your code. This can help you identify where errors are occurring and what values are being passed to variables.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Your script goes here</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Value of variable x is: <span class="hljs-variable">$x</span>"</span>

<span class="hljs-comment"># More code goes here</span>
</code></pre>
<h3 id="heading-use-the-set-e-option">Use the <code>set -e</code> option</h3>
<p>If you want your script to exit immediately when any command in the script fails, you can use the <code>set -e</code> option. This option will cause Bash to exit with an error if any command in the script fails, making it easier to identify and fix errors in your script.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">set</span> -e

<span class="hljs-comment"># Your script goes here</span>
</code></pre>
<h3 id="heading-troubleshooting-crons-by-verifying-logs">Troubleshooting crons by verifying logs</h3>
<p>We can troubleshoot crons using the log files. Logs are maintained for all the scheduled jobs. You can check and verify in logs if a specific job ran as intended or not.</p>
<p>For Ubuntu/Debian, you can find <code>cron</code>logs at:</p>
<pre><code class="lang-bash">/var/<span class="hljs-built_in">log</span>/syslog
</code></pre>
<p>The location varies for other distributions.</p>
<p> A cron job log file can look like this:</p>
<pre><code class="lang-bash">2022-03-11 00:00:01 Task started
2022-03-11 00:00:02 Running script /path/to/script.sh
2022-03-11 00:00:03 Script completed successfully
2022-03-11 00:05:01 Task started
2022-03-11 00:05:02 Running script /path/to/script.sh
2022-03-11 00:05:03 Error: unable to connect to database
2022-03-11 00:05:03 Script exited with error code 1
2022-03-11 00:10:01 Task started
2022-03-11 00:10:02 Running script /path/to/script.sh
2022-03-11 00:10:03 Script completed successfully
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we started with how to access the terminal and then ran some basic bash commands. We also studied what a bash shell is. We briefly looked at branching the code using loops and conditionals. Finally, we discussed automating the scripts using cron followed by some troubleshooting techniques.</p>
<h3 id="heading-resources-for-learning-more-about-bash-scripting">Resources for learning more about Bash scripting</h3>
<p>If you want to dig deeper into the world of bash scripting, I would suggest you have a look at this 6-hour course on Linux at freeCodeCamp.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/sWbUDq4S6Y8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>What’s your favorite thing you learned from this tutorial? You can also connect with me on any of these <a target="_blank" href="https://zaira_.bio.link/">platforms</a>. 📧�</p>
<p>See you in the next tutorial, happy coding 😁</p>
<p>Banner image credits: Image by <a target="_blank" href="https://www.freepik.com/free-vector/hand-drawn-flat-design-devops-illustration_25726540.htm#query=programmer%20linux&amp;position=4&amp;from_view=search&amp;track=ais">Freepik</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Setting a Static IP in Ubuntu – Linux IP Address Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ In most network configurations, the router DHCP server assigns the IP address dynamically by default. If you want to ensure that your system IP stays the same every time, you can force it to use a static IP.  That's what we will learn in this article... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/setting-a-static-ip-in-ubuntu-linux-ip-address-tutorial/</link>
                <guid isPermaLink="false">66adea771ad24d82983fd255</guid>
                
                    <category>
                        <![CDATA[ computer network ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ubuntu ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Thu, 02 Mar 2023 21:24:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/setting-static-ip-ubuntu.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In most network configurations, the router DHCP server assigns the IP address dynamically by default. If you want to ensure that your system IP stays the same every time, you can force it to use a static IP. </p>
<p>That's what we will learn in this article. We will explore two ways to set a static IP in Ubuntu.</p>
<p>Static IP addresses find their use in the following situations:</p>
<ul>
<li>Configuring port forwarding.</li>
<li>Configuring your system as a server such as an FTP server, web server, or a media server.</li>
</ul>
<p><strong>Pre-requisites:</strong></p>
<p>To follow this tutorial you will need the following:</p>
<ul>
<li>Ubuntu installation, preferably with a GUI.</li>
<li><code>sudo</code> rights as we will be modifying system configuration files.</li>
</ul>
<h2 id="heading-how-to-set-a-static-ip-using-the-command-line">How to Set a Static IP Using the Command Line</h2>
<p>In this section, we will explore all the steps in detail needed to configure a static IP.</p>
<h3 id="heading-step-1-launch-the-terminal">Step 1: Launch the terminal</h3>
<p>You can launch the terminal using the shortcut <code>Ctrl+ Shift+t</code>. </p>
<h3 id="heading-step-2-note-information-about-the-current-network">Step 2: Note information about the current network</h3>
<p>We will need our current network details such as the current assigned IP, subnet mask, and the network adapter name so that we can apply the necessary changes in the configurations.</p>
<p>Use the command below to find details of the available adapters and the respective IP information.</p>
<pre><code class="lang-bash">ip a
</code></pre>
<p>The output will look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>For my network, the current adapter is <code>eth0</code>. It could be different for your system</p>
<ul>
<li><strong>Note the current network adapter name</strong></li>
</ul>
<p>As my current adapter is <code>eth0</code>, the below details are relevant.</p>
<pre><code class="lang-bash">6: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:df:c3:ad brd ff:ff:ff:ff:ff:ff
    inet 172.23.199.129/20 brd 172.23.207.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::215:5dff:fedf:c3ad/64 scope link
       valid_lft forever preferred_lft forever
</code></pre>
<p>It is worth noting that the current IP <code>172.23.199.129</code> is dynamically assigned. It has <code>20</code> bits reserved for the netmask. The broadcast address is <code>172.23.207.255</code>.</p>
<ul>
<li><strong>Note the subnet</strong></li>
</ul>
<p>We can find the subnet mask details using the command below:</p>
<pre><code class="lang-bash">ifconfig -a
</code></pre>
<p>Select the output against your adapter and read it carefully.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-15.png" alt="Image" width="600" height="400" loading="lazy">
<em>IP is <code>172.23.199.129</code> and subnet mask is <code>255.255.240.0</code></em></p>
<p>Based on the class and subnet mask, the usable host IP range for my network is: <code>172.23.192.1 - 172.23.207.254</code>.</p>
<p>Subnetting is a vast topic. For more info on subnetting and your usable IP ranges, check out this <a target="_blank" href="https://www.freecodecamp.org/news/subnet-cheat-sheet-24-subnet-mask-30-26-27-29-and-other-ip-address-cidr-network-references/">article</a>.</p>
<h3 id="heading-step-3-make-configuration-changes">Step 3: Make configuration changes</h3>
<p><a target="_blank" href="https://netplan.io/">Netplan</a> is the default network management tool for the latest Ubuntu versions. Configuration files for Netplan are written using YAML and end with the extension <code>.yaml</code>.</p>
<p>Note: Be careful about spaces in the configuration file as they are part of the syntax. Without proper indentation, the file won't be read properly.</p>
<ul>
<li>Go to the <code>netplan</code> directory located at <code>/etc/netplan</code>.</li>
</ul>
<p><code>ls</code> into the <code>/etc/netplan</code> directory.</p>
<p>If you do not see any files, you can create one. The name could be anything, but by convention, it should start with a number like <code>01-</code> and end with <code>.yaml</code>. The number sets the priority if you have more than one configuration file. </p>
<p>I'll create a file named <code>01-network-manager-all.yaml</code>. </p>
<p>Let's add these lines to the file. We'll build the file step by step.</p>
<pre><code class="lang-bash">network:
 version: 2
</code></pre>
<p>The top-level node in a Netplan configuration file is a <code>network:</code> mapping that contains <code>version: 2</code> (means that it is using network definition version 2).</p>
<p>Next, we'll add a renderer, that controls the overall network. The renderer is <code>systemd-networkd</code> by default, but we'll set it to <code>NetworkManager</code>.</p>
<p>Now, our file looks like this:</p>
<pre><code class="lang-bash">network:
 version: 2
 renderer: NetworkManager
</code></pre>
<p>Next, we'll add <code>ethernets</code> and refer to the network adapter name we looked for earlier in step#2. Other device types supported are <code>modems:</code>, <code>wifis:</code>, or <code>bridges:</code>.</p>
<pre><code class="lang-bash">network:
 version: 2
 renderer: NetworkManager
 ethernets:
   eth0:
</code></pre>
<p>As we are setting a static IP and we do not want to dynamically assign an IP to this network adapter, we'll set <code>dhcp4</code> to <code>no</code>.</p>
<pre><code class="lang-bash">network:
 version: 2
 renderer: NetworkManager
 ethernets:
   eth0:
     dhcp4: no
</code></pre>
<p>Now we'll specify the specific static IP we noted in step #2 depending on our subnet and the usable IP range. It was <code>172.23.207.254</code>.</p>
<p>Next, we'll specify the gateway, which is the router or network device that assigns the IP addresses. Mine is on <code>192.168.1.1</code>.</p>
<pre><code class="lang-bash">network:
 version: 2
 renderer: NetworkManager
 ethernets:
   eth0:
     dhcp4: no
     addresses: [172.23.207.254/20]
     gateway4: 192.168.1.1
</code></pre>
<p>Next, we'll define <code>nameservers</code>. This is where you define a DNS server or a second DNS server. Here the first value is  <code>8.8.8.8</code> which is Google's primary DNS server and the second value is <code>8.8.8.4</code> which is Google's secondary DNS server. These values can vary depending on your requirements.</p>
<pre><code class="lang-bash">network:
 version: 2
 renderer: NetworkManager
 ethernets:
   eth0:
     dhcp4: no
     addresses: [172.23.207.254/20]
     gateway4: 192.168.1.1
     nameservers:
         addresses: [8.8.8.8,8.8.8.4]
</code></pre>
<h3 id="heading-step-4-apply-and-test-the-changes">Step 4: Apply and test the changes</h3>
<p>We can test the changes first before permanently applying them using this command:</p>
<pre><code class="lang-bash">sudo netplan try
</code></pre>
<p>If there are no errors, it will ask if you want to apply these settings.</p>
<p>Now, finally, test the changes with the command <code>ip a</code> and you'll see that the static IP has been applied.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-17.png" alt="Image" width="600" height="400" loading="lazy">
<em>Static IP applied</em></p>
<h2 id="heading-how-to-set-a-static-ip-using-the-gui">How to Set a Static IP Using the GUI</h2>
<p>It is very easy to set a static IP through the Ubuntu GUI/ Desktop. Here are the steps:</p>
<ul>
<li>Search for <code>settings</code>.</li>
<li>Click on either Network or Wi-Fi tab, depending on the interface you would like to modify.</li>
<li>To open the interface settings, click on the gear icon next to the interface name.</li>
<li>Select “Manual” in the IPV4 tab and enter your static IP address, Netmask and Gateway. </li>
<li>Click on the <code>Apply</code> button.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-16.png" alt="Image" width="600" height="400" loading="lazy">
<em>Manually setting a static IP using Ubuntu Desktop.</em></p>
<ul>
<li>Verify by using the command <code>ip a</code></li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-18.png" alt="Image" width="600" height="400" loading="lazy">
<em>Static IP updated via GUI</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we covered two methods to set the static IP in Ubuntu. I hope you found the article useful.</p>
<p>What’s your favorite thing you learned from this tutorial? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Grep Command in Linux – Usage, Options, and Syntax Examples ]]>
                </title>
                <description>
                    <![CDATA[ Grep is a useful command to search for matching patterns in a file. grep is short for "global regular expression print".  If you are a system admin who needs to scrape through log files or a developer trying to find certain occurrences in the code fi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/grep-command-in-linux-usage-options-and-syntax-examples/</link>
                <guid isPermaLink="false">66adea3af928a14f7c42c351</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Tue, 17 Jan 2023 22:40:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Copy-of-Copy-of-Cast-a-Function-in-SQL---Convert-Char-to-Int-SQL-Server-Example.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><code>Grep</code> is a useful command to search for matching patterns in a file. <code>grep</code> is short for "global regular expression print". </p>
<p>If you are a system admin who needs to scrape through log files or a developer trying to find certain occurrences in the code file, then <code>grep</code> is a powerful command to use.</p>
<p>In this article, we will discuss the <code>grep</code> command's syntax and its usage with some examples.</p>
<h2 id="heading-syntax-of-the-grep-command">Syntax of the <code>grep</code> Command</h2>
<p> The syntax of the <code>grep</code> command is as follows:</p>
<pre><code class="lang-bash">grep [OPTION...] PATTERNS [FILE...]
</code></pre>
<p>In the above syntax, grep searches for PATTERNS in each FILE. <code>Grep</code> finds each line that matched the provided PATTERN. It is a good practice to close the PATTERN in quotes when <code>grep</code> is used in a shell command.</p>
<p>In this article, we will discuss the following options that can be used with <code>grep</code>:</p>
<ul>
<li><code>-i</code>, <code>--ignore-case</code>: Ignores case distinctions in patterns and input data.</li>
<li><code>-v</code>, <code>--invert-match</code>: Selects the non-matching lines of the provided input pattern.</li>
<li><code>-n</code>, <code>--line-number</code>: Prefix each line of the matching output with the line number in the input file.</li>
<li><code>-w</code>: Find the exact matching word from the input file or string.</li>
<li><code>-c</code>: Count the number of occurrences of the provided pattern.</li>
</ul>
<p>In the coming examples, we will use the file <code>fruits.txt</code> with the following content: </p>
<pre><code>apples and pears
citrus – oranges, grapefruits, mandarins and limes
stone fruit – nectarines, apricots, peaches and plums
tropical and exotic – bananas and mangoes
berries – strawBERRIES, raspberries, blueberries, kiwifruit and passionfruit
melons – watermelons, rockmelons and honeydew melons
tomatoes and avocados.
</code></pre><h2 id="heading-how-to-find-a-matching-string-with-grep">How to Find a Matching String with <code>grep</code></h2>
<p>If we want to find the string "fruit" in the file <code>fruits.txt</code>, we can do so like this:</p>
<pre><code class="lang-bash">grep <span class="hljs-string">"fruit"</span> fruits.txt
</code></pre>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-73.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-ignore-case-distinctions-using-i">How to Ignore Case Distinctions using <code>-i</code></h2>
<p>We can command <code>grep</code> to return results while ignoring the case of the matching string. Let's find the word "berries" from our sample file. It should match all occurrences of "berries" regardless of their case.</p>
<pre><code class="lang-bash"> grep -i <span class="hljs-string">"berries"</span> fruits.txt
</code></pre>
<p> Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-74.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-select-the-non-matching-lines-using-v">How to Select the Non-Matching Lines using <code>-v</code></h2>
<p>We can reverse the results of the <code>grep</code> command to include non-matching results. Let's say, if we want to get all the lines that do not contain the word "berries", the command would look like this: </p>
<pre><code class="lang-bash">grep -v <span class="hljs-string">"berries"</span> fruits.txt
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-75.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The output returned all the lines that do not contain "berries".</p>
<h2 id="heading-how-to-find-the-line-numbers-against-matching-input-using-n">How to Find the Line Numbers Against Matching Input using <code>-n</code></h2>
<p>There are times when we want to get the line numbers against the matching string. For that, we can supply the <code>-n</code> flag to <code>grep</code> like this:</p>
<pre><code class="lang-bash"> grep -n <span class="hljs-string">"berries"</span> fruits.txt
</code></pre>
<p>Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-76.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the output, we can see that the word "berries" occurs on line #5 of the file.</p>
<h2 id="heading-how-to-find-the-exact-matching-word-from-the-input-file-or-string-using-w">How to Find the Exact Matching Word from the Input File or String using <code>-w</code></h2>
<p>If you were to match an exact word rather than just the occurrence of a pattern, you can do so by using the <code>-w</code> flag.</p>
<p>If we <code>grep</code> "fruit" without any flags, it would return any occurrence of the word "fruit".  This would include occurrences like "grape<strong>fruit</strong>", "dragon<strong>fruit</strong>" and so on like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-77.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But, if we only want "fruit" in our results, we can use the <code>-w</code> flag like this:</p>
<pre><code class="lang-bash"> grep -w  <span class="hljs-string">"fruit"</span> fruits.txt
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-78.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Do you see the difference? The latter result returned only one line where the exact word "fruit" was found.</p>
<h2 id="heading-how-to-count-the-number-of-occurrences-of-the-provided-pattern-using-c">How to Count the Number of Occurrences of the Provided Pattern using <code>-c</code></h2>
<p>We can count the number of times the matched string appears in the file. This is how the <code>-c</code> flag works:</p>
<pre><code class="lang-bash">grep -c <span class="hljs-string">"fruit"</span> fruits.txt
</code></pre>
<p>Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-79.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The word "fruit" appears 3 times in the file.</p>
<p>Tip: The <code>-c</code> flag can be very useful if you have to count the number of times an error message appeared in a log file. </p>
<h2 id="heading-how-to-scan-files-for-matching-input">How to Scan Files for Matching Input</h2>
<p>Until now we had discussed how to search for matching patterns in a file or input string. We can also use <code>grep</code> to narrow down the files that contain a matching pattern. We can use the following flags to separate files that contain the matching pattern:</p>
<ul>
<li><code>-l, --files-with-matches</code>: Prints the file name that contains the provided matching pattern.</li>
<li><code>-L, --files-without-match</code>: Prints the file name that does not contain the provided matching pattern.</li>
</ul>
<p>Let's say we have the following files in our folder:</p>
<pre><code class="lang-bash">zaira@Zaira:~/grep-tutorial$ ls -lrt
total 12
-rw-r--r-- 1 zaira zaira 327 Jan 16 19:25 fruits.txt
-rw-r--r-- 1 zaira zaira  47 Jan 16 20:31 vegetables.txt
-rw-r--r-- 1 zaira zaira 194 Jan 16 20:33 more-fruits.txt
</code></pre>
<p> The files have the following content:</p>
<pre><code>zaira@Zaira:~/grep-tutorial$ cat fruits.txt
apples and pears
citrus – oranges, grapefruits, mandarins and limes
stone fruit – nectarines, apricots, peaches and plums
tropical and exotic – bananas and mangoes
berries – strawBERRIES, raspberries, blueberries, kiwifruit and passionfruit
melons – watermelons, rockmelons and honeydew melons
tomatoes and avocados.
</code></pre><pre><code class="lang-bash">zaira@Zaira:~/grep-tutorial$ cat more-fruits.txt
passionfruit
dragon fruit
kiwis
pears
grapefruits, mandarins and limes
stone fruit – nectarines, apricots, peaches and plums
tropical and exotic – bananas and mangoes
tomatoes and avocados.
</code></pre>
<pre><code class="lang-bash">zaira@Zaira:~/grep-tutorial$ cat vegetables.txt
<span class="hljs-comment"># Vegetables only</span>

Cabbage
Onion
Carrot
Potato
</code></pre>
<p>Next, we want to see files that contain the pattern "fruit". We can do that like this:</p>
<pre><code class="lang-bash"> grep -l <span class="hljs-string">"fruit"</span> *
</code></pre>
<p>Note that the <code>*</code> searches for all the files in the folder.</p>
<p>Here is the output::</p>
<pre><code class="lang-bash">zaira@Zaira:~/grep-tutorial$  grep -l <span class="hljs-string">"fruit"</span> *
fruits.txt
more-fruits.txt
</code></pre>
<p>Let's say we want to list files that do not contain the word "fruit". We can achieve that using the command below:</p>
<pre><code class="lang-bash"> grep -L <span class="hljs-string">"fruit"</span> *
</code></pre>
<p>Here is the output:</p>
<pre><code class="lang-bash">zaira@Zaira:~/grep-tutorial$  grep -L <span class="hljs-string">"fruit"</span> *
vegetables.txt
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>If you want to study the <code>grep</code> command in depth, have a look at the man pages. You can get additional information on the command line with <code>grep --help</code>.</p>
<p>I hope you found this tutorial helpful!</p>
<p>What’s your favorite thing you learned from this tutorial? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
<p>Image credits:</p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/electronic-documents-management-doodle-concept_29314820.htm#query=file%20search&amp;position=7&amp;from_view=search&amp;track=sph">Image by upklyak</a> on Freepik</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make a File in Linux from the Command Line – Create a File in the Terminal ]]>
                </title>
                <description>
                    <![CDATA[ Managing files from the command line is one of the most common tasks for a Linux user.  Files are created, edited, deleted, and used by many of the background OS processes. Files are also used by regular users to accomplish daily tasks such as taking... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-a-file-in-linux-from-the-command-line-create-a-file-in-terminal/</link>
                <guid isPermaLink="false">66adea451ad24d82983fd24f</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Thu, 05 Jan 2023 18:58:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Copy-of-Copy-of-read-write-files-python--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Managing files from the command line is one of the most common tasks for a Linux user. </p>
<p>Files are created, edited, deleted, and used by many of the background OS processes. Files are also used by regular users to accomplish daily tasks such as taking notes, writing code, or simply duplicating content.</p>
<p>In this article, we will see three methods through which we can create files using the terminal. The three commands that we'll discuss are <code>touch</code>, <code>cat</code> and <code>echo</code>.</p>
<h3 id="heading-pre-requisites">Pre-requisites:</h3>
<p>You should have access to the Linux terminal to try out the commands mentioned in this tutorial. You can access the terminal in either of the following ways:</p>
<ul>
<li>Install a Linux distro of your choice on your system. </li>
<li>Use WSL (Windows Subsystem for Linux), if you want to use Windows and Linux side by side. <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-wsl2-windows-subsystem-for-linux-2-on-windows-10/">Here</a> is a guide to do that.</li>
<li>Use <a target="_blank" href="https://replit.com/">Replit</a> which is a browser-based IDE. You can create a Bash project and access the terminal right away.</li>
</ul>
<h2 id="heading-method-1-how-to-create-files-using-the-touch-command">Method #1: How to Create Files Using the <code>touch</code> Command</h2>
<p>The <code>touch</code> command creates empty files. You can use it to create multiple files as well.</p>
<p><strong>Syntax of the <code>touch</code> command:</strong></p>
<pre><code class="lang-bash"> touch FILE_NAME
</code></pre>
<p><strong>Examples of the <code>touch</code> command:</strong></p>
<p>Let's create a single empty file using the syntax provided above.</p>
<pre><code class="lang-bash">touch access.log
</code></pre>
<p>Next, we'll create multiple files by providing the file names separated with spaces after the <code>touch</code> command. </p>
<pre><code class="lang-bash">touch mod.log messages.log security.log
</code></pre>
<p>The above command will create three separate empty files named <code>mod.log</code>, <code>messages.log</code>, and <code>security.log</code>.</p>
<h2 id="heading-method-2-how-to-create-files-using-the-cat-command">Method #2: How to Create Files Using the <code>cat</code> Command</h2>
<p>The <code>cat</code> command is most commonly used to view the contents of a file. But you can also use it to create files.</p>
<p><strong>Syntax of the <code>cat</code> command:</strong></p>
<pre><code class="lang-bash">cat &gt; filename
</code></pre>
<p>This will ask you to enter the text that you can save and exit by pressing <code>ctrl+c</code>.</p>
<pre><code class="lang-bash">cat &gt; sample.txt
</code></pre>
<p> When I enter the above command, my terminal output looks like this:</p>
<pre><code class="lang-bash">zaira@Zaira:~$ cat &gt; sample.txt
This is a sample file created using the <span class="hljs-string">"cat"</span> <span class="hljs-built_in">command</span>
^C
</code></pre>
<p>Note the <code>^C</code> sign, which corresponds to <code>Ctrl+c</code> and signals to the terminal to save and exit.</p>
<p>Here are the contents of the created file:</p>
<pre><code class="lang-bash">zaira@Zaira:~$ more sample.txt
This is a sample file created using the <span class="hljs-string">"cat"</span> <span class="hljs-built_in">command</span>
</code></pre>
<h2 id="heading-method-3-how-to-create-files-using-the-echo-command">Method #3: How to Create Files Using the <code>echo</code> Command</h2>
<p>The <code>echo</code> command is used to add and append text to files. It also creates the file if it doesn't already exist.</p>
<p><strong>Syntax of the <code>echo</code> command:</strong></p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"some text"</span> &gt; sample.txt
</code></pre>
<p>or</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"some text"</span> &gt;&gt; sample.txt
</code></pre>
<p>The difference between <code>&gt;</code> and <code>&gt;&gt;</code> is that <code>&gt;</code> overwrites the file if it exists whereas <code>&gt;&gt;</code> appends to the existing file. </p>
<p>If you would like to follow along with the video tutorial of this article, here is the link:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/IQ8R7br-EuY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we discussed three different methods to create files in the Linux command line. I hope you found this tutorial helpful.</p>
<p>What’s your favorite thing you learned from this tutorial? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Bash If Statement – Linux Shell If-Else Syntax Example ]]>
                </title>
                <description>
                    <![CDATA[ When coding, you might need to make decisions based on certain conditions. Conditions are expressions that evaluate to a boolean expression (true or false). Statements that help to execute different code branches based on certain conditions are known... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/bash-if-statement-linux-shell-if-else-syntax-example/</link>
                <guid isPermaLink="false">66adea216778e7bd69427bba</guid>
                
                    <category>
                        <![CDATA[ Bash ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Mon, 14 Nov 2022 15:37:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/Copy-of-Copy-of-read-write-files-python--4-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When coding, you might need to make decisions based on certain conditions. Conditions are expressions that evaluate to a boolean expression (<code>true</code> or <code>false</code>).</p>
<p>Statements that help to execute different code branches based on certain conditions are known as conditional statements.</p>
<p><code>if...else</code> is one of the most commonly used conditional statements. Like other programming languages, Bash scripting also supports <code>if...else</code> statements. And we will study that in detail in this blog post.</p>
<h2 id="heading-syntax-of-if-statements">Syntax of <code>if</code> Statements</h2>
<p>You can use <code>if</code> statements in a variety of ways. The generic structure of <code>if</code> statements is as follows:</p>
<ul>
<li>Using an <code>if</code> statement only: <code>if...then...fi</code> </li>
<li>Using and <code>if</code> with an <code>else</code> statement: <code>if...then...else...fi</code> statements</li>
<li>Using multiple <code>else</code> statements with <code>if</code>: <code>if..elif..else..fi</code></li>
</ul>
<p>## </p>
<h2 id="heading-how-to-use-the-if-statement">How to Use the <code>if</code> Statement</h2>
<p>When you are using a single <code>if</code> statement, the syntax is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ condition ]
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">fi</span>
</code></pre>
<blockquote>
<p>Note that the spaces are part of the syntax and should not be removed.</p>
</blockquote>
<p>Let's go through an example where we are comparing two numbers to find if the first number is the smaller one.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#! /bin/sh</span>

a=5
b=30

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -lt <span class="hljs-variable">$b</span> ]
<span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"a is less than b"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p>If you run the above snippet, the condition <code>if [ $a -lt $b ]</code> evaluates to <code>True</code> , and the statement inside the if statement executes</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">a is less than b
</code></pre>
<h2 id="heading-how-to-use-the-if-else-statement">How to Use the <code>if .. else</code> Statement</h2>
<p>When you are using an <code>if</code> statement and you want to add another condition, the syntax is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ condition ]
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<p>Let's see an example where we want to find if the first number is greater or smaller than the second one. Here, <code>if [ $a -lt $b ]</code> evaluates to false, which causes the <code>else</code> part of the code to run. </p>
<pre><code class="lang-bash"><span class="hljs-meta">#! /bin/sh</span>

a=99
b=45

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -lt <span class="hljs-variable">$b</span> ]
<span class="hljs-keyword">then</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"a is less than b"</span>
<span class="hljs-keyword">else</span>
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"a is greater than b"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">a is greater than b
</code></pre>
<h2 id="heading-how-to-use-ifelifelse-statements">How to Use <code>if..elif..else</code> Statements</h2>
<p>Let's say you want to add further conditions and comparisons to make the code dynamic. In this case, the syntax would look like this:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ condition ]
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">elif</span> [ condition ] 
<span class="hljs-keyword">then</span>
    statement 
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<p>To create meaningful comparisons, we can use AND <code>-a</code> and OR <code>-o</code> as well.</p>
<p>In this example, we will determine the type of triangle using these conditions:</p>
<ul>
<li><code>Scalene</code>:  A triangle where every side is different in length.</li>
<li><code>Isosceles</code>: A triangle where 2 sides are equal.</li>
<li><code>Equilateral</code>: A triangle where all sides are equal.</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-built_in">read</span> a
<span class="hljs-built_in">read</span> b
<span class="hljs-built_in">read</span> c

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> == <span class="hljs-variable">$b</span> -a <span class="hljs-variable">$b</span> == <span class="hljs-variable">$c</span> -a <span class="hljs-variable">$a</span> == <span class="hljs-variable">$c</span> ]
<span class="hljs-keyword">then</span>
<span class="hljs-built_in">echo</span> EQUILATERAL

<span class="hljs-keyword">elif</span> [ <span class="hljs-variable">$a</span> == <span class="hljs-variable">$b</span> -o <span class="hljs-variable">$b</span> == <span class="hljs-variable">$c</span> -o <span class="hljs-variable">$a</span> == <span class="hljs-variable">$c</span> ]
<span class="hljs-keyword">then</span>
<span class="hljs-built_in">echo</span> ISOSCELES
<span class="hljs-keyword">else</span>
<span class="hljs-built_in">echo</span> SCALENE

<span class="hljs-keyword">fi</span>
</code></pre>
<p>In the example above, the script would ask the user to enter the three sides of the triangle. Next, it would compare the sides and decide the triangle type.</p>
<pre><code><span class="hljs-number">3</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
SCALENE
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>You can easily branch your code based on conditions like <code>if..else</code> and make the code more dynamic. In this tutorial, you learned the syntax of <code>if...else</code> along with some examples.  </p>
<p>I hope you found this tutorial helpful.</p>
<p>What’s your favorite thing you learned from this tutorial? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Set an Environment Variable in Linux ]]>
                </title>
                <description>
                    <![CDATA[ In programming, you use variables to store information like strings and numbers temporarily.  Variables can be used repeatedly throughout the code or by your operating system to provide values. You can edit them, overwrite them, and delete them. In t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-an-environment-variable-in-linux/</link>
                <guid isPermaLink="false">66adea523e5f4cf98adbcf44</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 26 Oct 2022 18:38:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/Copy-of-Copy-of-read-write-files-python--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In programming, you use variables to store information like strings and numbers temporarily. </p>
<p>Variables can be used repeatedly throughout the code or by your operating system to provide values. You can edit them, overwrite them, and delete them.</p>
<p>In this tutorial, I'll teach you what environment variables are and how to set them in Linux. </p>
<h2 id="heading-what-are-environment-variables">What Are Environment Variables?</h2>
<p>Environment variables are the variables specific to a certain environment. For example, each user in an operating system has its own environment. An admin user has a different environment than other users do, for example. </p>
<p>You might declare an environment variable only required by your user (for example a secret token) that doesn't need to be exposed to other users. </p>
<p>Here are some examples of environment variables in Linux:</p>
<ul>
<li><code>USER</code> – This points to the currently logged-in user.</li>
<li><code>HOME</code> – This shows the home directory of the current user.</li>
<li><code>SHELL</code> – This stores the path of the current user’s shell, such as bash or zsh.</li>
<li><code>LANG</code> – This variable points to the current language/locales settings.</li>
<li><code>MAIL</code> – This shows the location of where the current user’s mail is stored.</li>
</ul>
<p>These environment variables vary based on the current user session.</p>
<h2 id="heading-how-to-list-environment-variables-in-linux">How to List Environment Variables in Linux</h2>
<p>The command used to display all the environment variables defined for a current session is <code>env</code>. </p>
<p>Here is the output for my session:</p>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># env</span>
SHELL=/bin/bash
PWD=/root
LOGNAME=root
HOME=/root
LANG=C.UTF-8
LESSOPEN=| /usr/bin/lesspipe %s
USER=root
SHLVL=1
XDG_DATA_DIRS=/usr/<span class="hljs-built_in">local</span>/share:/usr/share:/var/lib/snapd/desktop
PATH=/usr/<span class="hljs-built_in">local</span>/sbin:/usr/<span class="hljs-built_in">local</span>/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/<span class="hljs-built_in">local</span>/games:/snap/bin
MAIL=/var/mail/root
_=/usr/bin/env
</code></pre>
<h2 id="heading-how-to-print-environment-variables-in-linux">How to Print Environment Variables in Linux</h2>
<p>There are two ways to print the already defined environment variables:</p>
<ul>
<li><code>printenv VARIABLE_NAME</code></li>
<li><code>echo $varname</code></li>
</ul>
<p>Let's print the value of the variable <code>SHELL</code> using both methods. Here's an example of printing using <code>printenv</code>:</p>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># printenv SHELL</span>
/bin/bash
</code></pre>
<p>And here's an example of using <code>echo</code>:</p>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># echo $SHELL</span>
/bin/bash
</code></pre>
<h2 id="heading-how-to-set-environment-variables-in-linux">How to Set Environment Variables in Linux</h2>
<p>The basic syntax to define an environment variable is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> VARIABLE_NAME=value
</code></pre>
<p>Let's define an environment variable, list it, and print its value.</p>
<ul>
<li>Define the variable <code>JAVA_HOME</code>:</li>
</ul>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># export JAVA_HOME=/usr/bin/java</span>
</code></pre>
<ul>
<li>Verify by listing it:</li>
</ul>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># env</span>
SHELL=/bin/bash
JAVA_HOME=/usr/bin/java
PWD=/root
LOGNAME=root
HOME=/root
LANG=C.UTF-8
LESSCLOSE=/usr/bin/lesspipe %s %s
TERM=xterm-256color
global22=yolo
LESSOPEN=| /usr/bin/lesspipe %s
USER=root
SHLVL=1
XDG_DATA_DIRS=/usr/<span class="hljs-built_in">local</span>/share:/usr/share:/var/lib/snapd/desktop
PATH=/usr/<span class="hljs-built_in">local</span>/sbin:/usr/<span class="hljs-built_in">local</span>/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/<span class="hljs-built_in">local</span>/games:/snap/bin
MAIL=/var/mail/root
_=/usr/bin/env
</code></pre>
<ul>
<li>Print its value:</li>
</ul>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># echo $JAVA_HOME</span>
/usr/bin/java
</code></pre>
<p>However, the variables defined using this method are stored for the current session only. They won't be available for the next session. </p>
<p>Let's verify by opening a new session and printing the variable's value.</p>
<pre><code class="lang-bash">zaira@Zaira:/etc$ <span class="hljs-built_in">echo</span> <span class="hljs-variable">$JAVA_HOME</span>
</code></pre>
<p>But, we can make the definitions persistent as shown in the next section.</p>
<h2 id="heading-how-to-make-environment-variables-persistent-in-linux">How to Make Environment Variables Persistent in Linux</h2>
<p>To make the <code>JAVE_HOME</code> variable persistent, edit the file <code>.bashrc</code> and define its value in it. </p>
<p>The <code>.bashrc</code> is a script file that's executed whenever a user logs in. It is hidden and located in the user's home directory by default. </p>
<p>I have edited my <code>.bashrc</code> file as follows:</p>
<pre><code class="lang-bash">vi ~/.bashrc
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-194.png" alt="Image" width="600" height="400" loading="lazy">
<em>Add the definition of the environment variable at the end of the <code>.bashrc</code> file</em></p>
<p>For the changes to take effect, update the <code>.bashrc</code>  file using the <code>source</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> .bashrc
</code></pre>
<p>Let's verify by opening a new session.</p>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># echo $JAVA_HOME</span>
/usr/bin/java
</code></pre>
<h2 id="heading-how-to-create-a-persistent-global-variable-in-linux">How to Create a Persistent Global Variable in Linux</h2>
<p>Sometimes you might need to define a global environment variable that is accessible by all users. </p>
<p>For that, we need to first declare a variable and make changes in relevant files where environment variables are read from.</p>
<p> Let's go step by step.</p>
<ol>
<li>I am logged in as the user <code>Zaira</code>. I am creating a global variable <code>GLOBAL_VARIABLE</code> like this:</li>
</ol>
<pre><code class="lang-bash">zaira@Zaira:~$ <span class="hljs-built_in">export</span> GLOBAL_VARIABLE=<span class="hljs-string">"This is a global variable"</span>
</code></pre>
<ol start="2">
<li><p>Edit the following files:</p>
</li>
<li><p><code>/etc/environment</code> – This file is used to set up system-wide environment variables.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-196.png" alt="Image" width="600" height="400" loading="lazy">
<em>Update the <code>/etc/environment</code> file</em></p>
<p>For the changes to take effect, use the command <code>source /etc/environment</code>.</p>
<ul>
<li><code>/etc/profile</code> – Variables set in this file are read whenever a bash shell is logged in. Edit this file and use the <code>export</code> command:</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-198.png" alt="Image" width="600" height="400" loading="lazy">
<em>Update the <code>/etc/profile</code></em></p>
<p>Time to test!</p>
<p>Now, I'll switch the user to the root user and verify if I can access the variable <code>GLOBAL_VARIABLE</code>.</p>
<pre><code class="lang-bash">root@Zaira:~<span class="hljs-comment"># echo $GLOBAL_VARIABLE</span>
This is a global variable
</code></pre>
<p>It worked! I have been able to access the global variable defined by the user <code>Zaira</code> through the <code>root</code> user as well. The same would apply to other users too. So now you also know how to define global environment variables.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned how to create and define environment variables in Linux. You also learned how to make them persistent so that you can use them across multiple sessions. </p>
<p>What’s your favorite thing you learned here? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/hacker-operating-laptop-cartoon-icon-illustration-technology-icon-concept-isolated-flat-cartoon-style_11602236.htm#query=programmer&amp;position=2&amp;from_view=search&amp;track=sph">Image by catalyststuff</a> on Freepik.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Rename a File in Linux – Bash Terminal Command ]]>
                </title>
                <description>
                    <![CDATA[ Renaming files is a very common operation whether you are using the command line or the GUI.  Compared to the GUI (or Graphical User Interface), the CLI is especially powerful. This is in part because you can rename files in bulk or even schedule the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rename-file-linux-bash-command/</link>
                <guid isPermaLink="false">66adea6ffebac312b7307573</guid>
                
                    <category>
                        <![CDATA[ Bash ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Fri, 30 Sep 2022 15:06:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/Copy-of-read-write-files-python--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Renaming files is a very common operation whether you are using the command line or the GUI. </p>
<p>Compared to the GUI (or Graphical User Interface), the CLI is especially powerful. This is in part because you can rename files in bulk or even schedule the scripts to rename files at a certain point in time.</p>
<p>In this tutorial, you will see how you can rename files in the Linux command line using the built-in <code>mv</code> command.</p>
<h2 id="heading-how-to-use-the-linux-mv-command">How to Use the Linux <code>mv</code> Command</h2>
<p>You can use the built-in Linux command <code>mv</code> to rename files. </p>
<p>The <code>mv</code> command follows this syntax:</p>
<pre><code class="lang-bash">mv [options] source_file destination_file
</code></pre>
<p>Here are some of the options that can come in handy with the <code>mv</code> command:</p>
<ul>
<li><code>-v</code> , <code>--verbose</code>: Explains what is being done.</li>
<li><code>-i</code>, <code>--interactive</code>: Prompts before renaming the file.</li>
</ul>
<p>Let's say you want to rename <code>index.html</code> to <code>web_page.html</code>. You use the <code>mv</code> command as follows:</p>
<pre><code class="lang-bash">zaira@Zaira:~/rename-files$ mv index.html web_page.html
</code></pre>
<p>Let's list the files and see if the file has been renamed:</p>
<pre><code class="lang-bash">zaira@Zaira:~/rename-files$ ls
web_page.html
</code></pre>
<h2 id="heading-how-to-name-files-in-bulk-using-mv">How to Name Files in Bulk Using <code>mv</code></h2>
<p>Let's discuss a script where you can rename files in a bulk using a loop and the <code>mv</code> command.</p>
<p>Here we have a list of files with the extension <code>.js</code>. </p>
<pre><code class="lang-bash">zaira@Zaira:~/rename-files$ ls -lrt
total 0
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 index.js
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 config.js
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 blog.js
</code></pre>
<p>Next, you want to convert them to <code>.html</code>.</p>
<p>You can use the command below to rename all the files in the folder:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> *.js; <span class="hljs-keyword">do</span> mv -- <span class="hljs-string">"<span class="hljs-variable">$f</span>"</span> <span class="hljs-string">"<span class="hljs-variable">${f%.js}</span>.html"</span>; <span class="hljs-keyword">done</span>
</code></pre>
<p>Let's break down this long string to see what's happening under the hood:</p>
<ul>
<li>The first part [<code>for f in *.js</code>] tells the <code>for</code> loop to process each “.js” file in the directory.</li>
<li>The next part [<code>do mv -- "$f" "${f%.js}.html</code>] specifies what the processing will do. It is using <code>mv</code> to rename each file. The new file is going to be named with the original file’s name excluding the <code>.js</code> part. A new extension of <code>.html</code> will be appended instead.</li>
<li>The last part [<code>done</code>] simply ends the loop once all the files have been processed.</li>
</ul>
<pre><code class="lang-bash">zaira@Zaira:~/rename-files$ ls -lrt
total 0
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 index.html
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 config.html
-rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 blog.html
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you can see, renaming files is quite easy using the CLI. It can be really powerful when deployed in a script.</p>
<p>What’s your favorite thing you learned here? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>You can read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/college-project-concept-illustration_29659818.htm">Image by storyset</a> on Freepik</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Remove a Directory in Linux – How to Remove folders from the Command Line ]]>
                </title>
                <description>
                    <![CDATA[ Linux is a powerful OS with various command line utilities to help you achieve your day-to-day tasks. Removing folders is a very common operation that allows you to either remove a single folder or remove them recursively (folders within folders).  I... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/remove-directory-in-linux-from-the-command-line/</link>
                <guid isPermaLink="false">66adea6ac537123a64ede808</guid>
                
                    <category>
                        <![CDATA[ command line ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Wed, 07 Sep 2022 18:18:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/Copy-of-read-write-files-python--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Linux is a powerful OS with various command line utilities to help you achieve your day-to-day tasks.</p>
<p>Removing folders is a very common operation that allows you to either remove a single folder or remove them recursively (folders within folders). </p>
<p>In this tutorial, we will see how we can delete folders from the command line.  </p>
<h3 id="heading-but-isnt-the-gui-enough-to-delete-folders">But isn't the GUI enough to delete folders?</h3>
<p>It is very simple to delete folders from the file explorer. All we need is to either use the delete button on the keyboard or right-click and delete the folder. But you can be more creative with the CLI (Command Line interface). </p>
<p>With the command line, you can create a script to remove files periodically. You can also remove files that match certain criteria such as modification time or size.</p>
<p>Housekeeping scripts also make use of commands to delete unwanted folders to keep disk space at an optimal level. </p>
<p>In short, you can automate your daily tasks using the command line.</p>
<p>Use caution when removing from the CLI. Once you delete a folder using the CLI, it is permanently deleted as there is no Recycle bin. The only way to recover is through a backup.</p>
<h2 id="heading-how-to-delete-an-empty-folder-using-rmdir">How to Delete an Empty Folder using <code>rmdir</code></h2>
<p>You use the <code>rmdir</code> command to delete an empty directory. It doesn't work on non-empty directories.</p>
<p><strong>Syntax of the <code>rmdir</code> command:</strong></p>
<pre><code class="lang-bash">rmdir [OPTION] DIRECTORY_NAME
</code></pre>
<p>We can supply the following options:</p>
<ul>
<li><code>-v</code> : displays the detailed output for every directory processed.</li>
<li><code>--ignore-fail-on-non-empty</code>: ignores if the directory is non-empty.</li>
<li><code>-p, --parents</code>: removes a directory and its ancestors. For example, <code>'rmdir -p a/b/c</code> would first remove the folder <code>c</code>, then <code>b</code> and then <code>a</code></li>
</ul>
<h2 id="heading-how-to-delete-a-non-empty-folder-using-rm">How to Delete a Non-Empty Folder using <code>rm</code></h2>
<p>We can not use <code>rmdir</code> on non-empty folders. We have another command for that – <code>rm</code>. </p>
<p><strong>Syntax of the <code>rm</code> command:</strong></p>
<pre><code class="lang-bash"> rm [OPTION] [FILE]
</code></pre>
<p>We can use the following options:</p>
<ul>
<li><code>-r</code>, <code>-R</code>, <code>--recursive</code>: removes directories and their contents recursively.</li>
<li><code>-d</code>, <code>--dir</code>: removes empty directories. So we can also use <code>rm</code> to remove empty directories like the <code>rmdir</code> command.</li>
<li><code>-v</code>, <code>--verbose</code>: explains what is being done by mentioning the folder details being processed.</li>
<li><code>-i</code>: prompts before every removal.</li>
</ul>
<p>So, the command to delete a non-empty folder would be:</p>
<pre><code>rm -r folder-name
</code></pre><h2 id="heading-how-to-force-delete-directories">How to Force Delete Directories</h2>
<p>If you do not have <code>write</code> permissions, you are unable to delete the folder. If you wish to delete it anyways, use the <code>-f</code> flag. The <code>-f</code> flag doesn't display any prompts. </p>
<h2 id="heading-how-to-safely-delete-folders-in-linux">How to Safely Delete Folders in Linux</h2>
<p>To prevent accidental deletion, use the <code>-i</code> interactive flag. This way you'll be prompted before deleting a folder and the contents inside it. </p>
<p>If you want to proceed, just answer the prompts by entering <code>y</code>. On the other hand, enter <code>n</code> to skip the file.</p>
<p>In the example below, note how we descend into the folder and check each file one by one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-309.png" alt="Image" width="600" height="400" loading="lazy">
<em>Interactively deleting a folder named <code>find-test</code></em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Removing directories is useful when you need to remove folders after archiving them, when deleting duplicates, when deleting unused folders, and much more.</p>
<p>All these tasks are targeted at creating more disk space. I hope you found this tutorial helpful.</p>
<p>What’s your favorite thing you learned here? Let me know on <a target="_blank" href="https://twitter.com/hira_zaira">Twitter</a>!</p>
<p>Read my other posts <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
