w3resource

Mastering Basic Bash Commands for System Monitoring and Management

1.

Displaying Disk Usage:

Write a Bash script that uses the df command to display disk usage information for all mounted filesystems.

Code:

#!/bin/bash
# Script to display disk usage information for all mounted filesystems

# Using df command to display disk usage
df -h
# -h option: Makes the output human-readable by showing sizes in powers of 1024 (e.g., K, M, G)

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
Filesystem      Size  Used Avail Use% Mounted on
rootfs          101G   93G  7.6G  93% /
root            101G   93G  7.6G  93% /root
home            101G   93G  7.6G  93% /home
data            101G   93G  7.6G  93% /data
cache           101G   93G  7.6G  93% /cache
mnt             101G   93G  7.6G  93% /mnt
none            101G   93G  7.6G  93% /dev
none            101G   93G  7.6G  93% /run
none            101G   93G  7.6G  93% /run/lock
none            101G   93G  7.6G  93% /run/shm
none            101G   93G  7.6G  93% /run/user
tmpfs           101G   93G  7.6G  93% /sys/fs/cgroup
C:\             101G   93G  7.6G  93% /mnt/c
D:\             245G   54G  191G  22% /mnt/d
E:\             245G   34G  211G  14% /mnt/e
F:\             245G   47G  198G  20% /mnt/f
G:\             199G  135G   65G  68% /mnt/g
H:\             151G  7.0G  145G   5% /mnt/h
I:\             196G   17G  179G   9% /mnt/i

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • This line is called the shebang. It tells the operating system to use the Bash shell to execute this script.
  • Command: df -h
    • df is a command-line utility that reports file system disk space usage.
    • The -h option stands for "human-readable". It makes the output easier to read by showing sizes in human-readable formats, such as kilobytes (K), megabytes (M), and gigabytes (G).

2.

Monitoring System Processes:

Write a Bash script that uses the ps command to display a list of all running processes.

Code:

#!/bin/bash
# Script to display a list of all running processes

# Using ps command to display running processes
ps -e
# -e option: Displays information about all processes

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
  PID TTY          TIME CMD
    1 ?        00:00:00 init
   13 tty1     00:00:00 init
   14 tty1     00:00:00 bash
   41 tty1     00:00:00 test1.sh
   42 tty1     00:00:00 ps

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Indicates that the script should be run using the Bash shell.
  • Command: ps -e
    • The ps command is used to display information about the currently running processes.
    • The -e option tells ps to show information about all processes running on the system, not just those associated with the current terminal session.

3.

Checking Free Memory:

Write a Bash script that uses the free command to display the amount of free and used memory in the system.

Code:

#!/bin/bash
# Script to display the amount of free and used memory

# Using free command to display memory usage
free -h
# -h option: Makes the output human-readable by showing sizes in powers of 1024 (e.g., K, M, G)

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
                    total        used        free      shared  buff/cache   available
Mem:            31G         10G         21G         17M        230M         21G
Swap:           12G        6.3M         12G

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: free -h
    • The free command is used to display the amount of free and used memory in the system.
    • The -h option makes the output more readable by showing memory sizes in human-friendly units, such as kilobytes (K), megabytes (M), and gigabytes (G).

4.

Viewing System Uptime:

Write a Bash script that uses the uptime command to display how long the system has been running.

Code:

#!/bin/bash
# Script to display system uptime

# Using uptime command to display how long the system has been running
Uptime

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
 08:13:40 up 40 min,  0 users,  load average: 0.52, 0.58, 0.59

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: uptime
    • The uptime command is used to display the current time, how long the system has been running, the number of users currently logged in, and the system load averages for the past 1, 5, and 15 minutes.

5.

Displaying CPU Information:

Write a Bash script that uses the lscpu command to display detailed information about the CPU architecture.

Code:

#!/bin/bash
# Script to display CPU information

# Using lscpu command to display CPU architecture details
lscpu

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                6
On-line CPU(s) list:   0-5
Thread(s) per core:    1
Core(s) per socket:    6
Socket(s):             1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 158
Model name:            Intel(R) Core(TM) i5-9400F CPU @ 2.90GHz
Stepping:              10
CPU MHz:               2904.000
CPU max MHz:           2904.0000
BogoMIPS:              5808.00
Virtualization:        VT-x
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave osxsave avx f16c rdrand lahf_lm abm 3dnowprefetch fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt ibrs ibpb stibp ssbd

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: lscpu
    • The lscpu command is used to display detailed information about the CPU architecture, including the number of CPUs, cores, threads, model name, speed, and other relevant details.

6.

Listing Open Network Connections:

Write a Bash script that uses the netstat command to list all open network connections and listening ports.

Code:

#!/bin/bash
# Script to list all open network connections and listening ports

# Using netstat command to list network connections
netstat -tuln
# -t option: Show TCP ports
# -u option: Show UDP ports
# -l option: Show listening ports
# -n option: Show numerical addresses instead of resolving hostnames

Output:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: netstat -tuln
    • The netstat command is used to display network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
    • The -t option shows TCP connections.
    • The -u option shows UDP connections.
    • The -l option displays only listening sockets.
    • The -n option shows numerical addresses instead of resolving hostnames.

7.

Displaying Logged-in Users:

Write a Bash script that uses the who command to display a list of all users currently logged into the system.

Code:

#!/bin/bash
# Script to display all users currently logged into the system

# Using who command to list logged-in users
who

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: who
    • The who command is used to display a list of all users currently logged into the system, along with their login details such as terminal, login time, and host information.

8.

Checking System Load:

Write a Bash script that uses the top command to display the system's load average and the most CPU-intensive tasks.

Code:

#!/bin/bash
# Script to display system load average and top CPU-intensive tasks

# Using top command to display system load and tasks
top -b -n 1 | head -n 20
# -b option: Run in batch mode for easier parsing
# -n 1 option: Limit to a single iteration
# head -n 20: Limit the output to the top 20 lines

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
top - 08:43:15 up  1:09,  0 users,  load average: 0.52, 0.58, 0.59
Tasks:   6 total,   1 running,   5 sleeping,   0 stopped,   0 zombie
%Cpu(s):  7.3 us,  2.6 sy,  0.0 ni, 90.0 id,  0.0 wa,  0.1 hi,  0.0 si,  0.0 st
KiB Mem : 33497092 total, 22588240 free, 10672376 used,   236476 buff/cache
KiB Swap: 13143676 total, 13137212 free,     6464 used. 22683860 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
    1 root      20   0    8952    332    288 S   0.0  0.0   0:00.03 init
   13 root      20   0    8952    232    188 S   0.0  0.0   0:00.01 init
   14 rg        20   0   15104   3576   3488 S   0.0  0.0   0:00.08 bash
   65 rg        20   0   13208   1348   1272 S   0.0  0.0   0:00.00 test1.sh
   66 rg        20   0   15768   1800   1324 R   0.0  0.0   0:00.00 top
   67 rg        20   0   12048    740    612 S   0.0  0.0   0:00.00 head

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: top -b -n 1 | head -n 20
    • The top command is used to display dynamic real-time information about system processes, including CPU and memory usage.
    • The -b option tells top to run in batch mode, which is useful for scripting.
    • The -n 1 option limits top to a single iteration, ensuring that it only displays information once.
    • The | (pipe) operator is used to pass the output of top to the head command.
    • The head -n 20 command limits the output to the top 20 lines, providing a summary of the most CPU-intensive tasks.

9.

Displaying File System Types:

Write a Bash script that uses the lsblk command to display information about block devices and their filesystems.

Code:

#!/bin/bash
# Script to display block device information and filesystems

# Using lsblk command to display block devices and filesystems
lsblk -f
# -f option: Output info about filesystems

Output:

NAME         FSTYPE LABEL UUID FSAVAIL FSUSE% MOUNTPOINT
loop0                                         
loop1                                         
loop2                                         
---------------
---------------
loop10                                        
loop11                                        
nvme0n1                                       
+-nvme0n1p1                      62.2G    36% /workspace
+-nvme0n1p14                                  
+-nvme0n1p15                                  
nvme1n1                                       [SWAP]

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Command: lsblk -f
    • The lsblk command is used to list information about block devices (such as hard drives and partitions) and their relationships with other devices in the system.
    • The -f option is used to display information about filesystems associated with the block devices, including filesystem type and label.

10.

Checking System Logs:

Write a Bash script that uses the tail command to display the last 20 lines of the system log file /var/log/syslog.

Code:

#!/bin/bash
# Script to display the last 20 lines of the system log file or using journalctl

# Check for the presence of the syslog file
if [ -f /var/log/syslog ]; then
    echo "Displaying the last 20 lines of /var/log/syslog:"
    tail -n 20 /var/log/syslog
elif [ -f /var/log/messages ]; then
    echo "Displaying the last 20 lines of /var/log/messages:"
    tail -n 20 /var/log/messages
else
    echo "Displaying the last 20 lines of the systemd journal:"
    journalctl -n 20
fi

Output:

rg@DESKTOP-3KE0KU4:~$ ./test1.sh
Displaying the last 20 lines of the systemd journal:
No journal files were found.
-- No entries --

Explanation:

In the exercise above,

  • Shebang Line: #!/bin/bash
    • Specifies that the script should be executed using the Bash shell.
  • Conditional Statement:
    • The script first checks if the file /var/log/syslog exists using the -f option of the test command [ -f /var/log/syslog ]. If it does, it means the system is using a log file named syslog (common in Debian-based systems).
    • If /var/log/syslog exists, it uses the tail command to display the last 20 lines of this log file.
    • If /var/log/syslog does not exist, it checks if the file /var/log/messages exists. This is common in Red Hat-based systems.
    • If /var/log/messages exists, it uses the tail command to display the last 20 lines of this log file.
    • If neither /var/log/syslog nor /var/log/messages exists, it assumes the system is using systemd and uses the journalctl command to display the last 20 lines of the systemd journal.

Bash Editor:


More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.