Fundamentals 22 min read

Master Bash: 40 Essential Shell Scripts Every Linux User Should Know

This comprehensive guide walks you through the fundamentals of Bash scripting on Linux, covering everything from a simple Hello World program and echo usage to loops, conditionals, functions, file manipulation, directory handling, and system maintenance, complete with clear code examples for each concept.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Bash: 40 Essential Shell Scripts Every Linux User Should Know

Historically, the shell has been the native command-line interpreter for Unix-like systems and remains a core feature of Linux, offering powerful shells such as Bash, Zsh, Tcsh, and Ksh, with programmability as a standout trait.

1.Hello World

Programmers often start learning a new language with a Hello World program that prints "Hello World" to standard output. Create a hello-world.sh file with the following content:

#!/bin/bash
 echo "Hello World"

Make the file executable: $ chmod a+x hello-world.sh Run it with either of these commands:

$ bash hello-world.sh
$ ./hello-world.sh

The script prints the echoed string.

2.Using echo to print

The echo command prints information in Bash, similar to C's printf. Create an echo.sh file:

#!/bin/bash
 echo "Printing text"
 echo -n "Printing text without newline"
 echo -e "
Removing\t special\t characters
"

Run the script to see the effects of the -e option.

3.Using comments

Comments improve documentation and are required for high-quality codebases. Use # to comment a line. Example:

#!/bin/bash
# Adding two values
((sum=25+35))
# Print the result
 echo $sum

The script outputs 60; the first line is a shebang.

4.Multi-line comments

Multi-line comments can be added using a colon and a quoted block:

#!/bin/bash
: '
This script calculates
the square of 5.
'
((area=5*5))
 echo $area

The script prints the substring.

5.While loop

The while construct repeats commands. Example while.sh:

#!/bin/bash
i=0
while [ $i -le 2 ]
do
 echo Number: $i
 ((i++))
done

Loop syntax:

while [ condition ]
do
 commands
... 
done

6.For loop

The for loop iterates efficiently:

#!/bin/bash
for (( counter=1; counter<=10; counter++ ))
do
 echo -n "$counter "
done
 printf "
"

7.Receiving user input

#!/bin/bash
 echo -n "Enter Something:"
 read something
 echo "You Entered: $something"

8.If statement

if CONDITION
then
 STATEMENTS
fi

Example:

#!/bin/bash
 echo -n "Enter a number:"
 read num
 if [[ $num -gt 10 ]]
 then
 echo "Number is greater than 10."
 fi

9.If-else control

#!/bin/bash
 read n
 if [ $n -lt 10 ];
 then
 echo "It is a one digit number"
 else
 echo "It is a two digit number"
 fi

10.Using AND operator

#!/bin/bash
 echo -n "Enter Number:"
 read num
 if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
 echo "EvenNumber"
 else
 echo "Odd Number"
 fi

11.Using OR operator

#!/bin/bash
 echo -n "Enter any number:"
 read n
 if [[ ( $n -eq 15 || $n -eq 45 ) ]]; then
 echo "You won"
 else
 echo "You lost!"
 fi

12.Using elif

#!/bin/bash
 echo -n "Enter a number: "
 read num
 if [[ $num -gt 10 ]];
 then
 echo "Number is greater than 10."
 elif [[ $num -eq 10 ]];
 then
 echo "Number is equal to 10."
 else
 echo "Number is less than 10."
 fi

13.Case condition

#!/bin/bash
 echo -n "Enter a number: "
 read num
 case $num in
 100)
 echo "Hundred!!" ;;
 200)
 echo "Double Hundred!!" ;;
 *)
 echo "Neither 100 nor 200" ;;
 esac

14.Command-line arguments

#!/bin/bash
 echo "Total arguments : $#"
 echo "First Argument = $1"
 echo "Second Argument = $2"

Run with $ ./test.sh Hey Howdy.

15.Named parameters

#!/bin/bash
 for arg in "$@"
 do
 index=$(echo $arg | cut -f1 -d=)
 val=$(echo $arg | cut -f2 -d=)
 case $index in
 X) x=$val;;
 Y) y=$val;;
 esac
done
 ((result=x+y))
 echo "X+Y=$result"

16.String concatenation

#!/bin/bash
string1="Ubuntu"
string2="Pit"
string=$string1$string2
 echo "$string is a great resource for Linux beginners."

17.String slicing

#!/bin/bash
Str="Learn Bash Commands from UbuntuPit"
subStr=${Str:0:20}
 echo $subStr

18.Cut for slicing

#!/bin/bash
Str="Learn Bash Commands from UbuntuPit"
subStr=$(echo $Str| cut -d ' ' -f 1-3)
 echo $subStr

19.Adding two values

#!/bin/bash
 echo -n "Enter first number:"
 read x
 echo -n "Enter second number:"
 read y
 (( sum=x+y ))
 echo "The result of addition=$sum"

20.Adding multiple values

#!/bin/bash
sum=0
for (( counter=1; counter<5; counter++ ))
do
 echo -n "Enter Your Number:"
 read n
 (( sum+=n ))
done
 printf "
"
 echo "Result is: $sum"

21.Bash functions

#!/bin/bash
function Add(){
 echo -n "Enter a Number: "
 read x
 echo -n "Enter another Number: "
 read y
 echo "Addition is: $(( x+y ))"
}
Add

22.Functions with return values

#!/bin/bash
function Greet(){
 str="Hello $name, what brings you to UbuntuPit.com?"
 echo $str
}
 echo "-> what's your name?"
 read name
 val=$(Greet)
 echo -e "-> $val"

23.Creating directories

#!/bin/bash
 echo -n "Enter directory name ->"
 read newdir
 cmd="mkdir $newdir"
 eval $cmd

24.Create directory if not exists

#!/bin/bash
 echo -n "Enter directory name ->"
 read dir
 if [ -d "$dir" ];
 then
 echo "Directory exists"
 else
 `mkdir $dir`
 echo "Directory created"
 fi

25.Read file

#!/bin/bash
file='editors.txt'
while read line; do
 echo $line
done < $file

26.Delete file

#!/bin/bash
 echo -n "Enter filename ->"
 read name
 rm -i $name

27.Append to file

#!/bin/bash
 echo "Before appending the file"
 cat editors.txt
 echo "6. NotePad++" >> editors.txt
 echo "After appending the file"
 cat editors.txt

28.Test file existence

#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
 echo "File exists"
else
 echo "File does not exist"
fi

29.Send email from script

#!/bin/bash
recipient="[email protected]"
subject="Greetings"
message="Welcome to UbuntuPit"
`mail -s $subject $recipient <<< $message`

30.Parse date and time

#!/bin/bash
year=`date +%Y`
month=`date +%m`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
second=`date +%S`
 echo `date`
 echo "Current Date is: $day-$month-$year"
 echo "Current Time is: $hour:$minute:$second"

31.sleep command

#!/bin/bash
 echo "How long to wait?"
 read time
 sleep $time
 echo "Waited for $time seconds!"

32.wait command

#!/bin/bash
 echo "Testing wait command"
 sleep 5 &
 pid=$!
 kill $pid
 wait $pid
 echo $pid was terminated.

33.Show most recently updated file

ls -lrt | grep ^- | awk 'END{print $NF}'

34.Add batch extensions

#!/bin/bash
dir=$1
for file in `ls $1/*`
do
 mv $file $file.UP
done

35.Count files or directories

#!/bin/bash
if [ -d "$@" ]; then
 echo "Files found: $(find "$@" -type f | wc -l)"
 echo "Folders found: $(find "$@" -type d | wc -l)"
else
 echo "[ERROR] Please retry with another folder."
 exit 1
fi

36.Clean log files

#!/bin/bash
LOG_DIR=/var/log
cd $LOG_DIR
cat /dev/null > messages
cat /dev/null > wtmp
 echo "Logs cleaned up."

37.Bash backup script

#!/bin/bash
BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}
find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
 echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."
 exit 0

38.Check if root user

#!/bin/bash
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]
then
 echo "You are root."
else
 echo "You are not root"
fi
 exit 0

39.Remove duplicate lines from file

#! /bin/sh
 echo -n "Enter Filename-> "
 read filename
 if [ -f "$filename" ]; then
 sort $filename | uniq | tee sorted.txt
 else
 echo "No $filename in $pwd...try again"
 fi
 exit 0

40.System maintenance

#!/bin/bash
 echo -e "
$(date "+%d-%m-%Y --- %T") --- Starting work
"
apt-get update
apt-get -y upgrade
apt-get -y autoremove
apt-get autoclean
 echo -e "
$(date "+%T") \t Script Terminated"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Automationcommand-lineSystem AdministrationBashShell scripting
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.