Master Bash: 40 Essential Shell Script Techniques for Linux

This comprehensive guide walks you through 40 practical Bash shell scripting examples—from a simple Hello World program to advanced file handling, conditionals, loops, functions, and system maintenance—showing how to write, execute, and debug scripts that automate everyday Linux tasks.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Bash: 40 Essential Shell Script Techniques for Linux

1. Hello World

Programmers often start with a Hello World program to learn a new language. Create a hello-world.sh file with the following content and make it executable.

#!/bin/bash
echo "Hello World"

Make the script executable with chmod a+x hello-world.sh and run it using bash hello-world.sh or ./hello-world.sh. It prints the string passed to echo.

2. Using echo

The echo command prints information in Bash. It supports options such as -n (no newline) and -e (interpret escape sequences). Example script:

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

3. Comments

Comments improve documentation. 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 ( #!/bin/bash) is a shebang, not a comment.

4. Multi‑line comments

Multi‑line comments can be simulated with a : command and a quoted block:

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

5. While loop

The while construct repeats commands while a condition is true.

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

6. For loop

The for loop iterates over a range or list.

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

7. Reading user input

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

8. If statement

if CONDITION
then
  STATEMENTS
fi

The statements execute only when the condition is true.

9. If‑else

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

10. AND operator

Use && to require multiple conditions.

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

11. OR operator

Use || to succeed when any condition is true.

#!/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. Elif

#!/bin/bash
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 statement

#!/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"

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. Substring extraction

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

18. Using cut for extraction

#!/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. 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 value

#!/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 a directory

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

24. Create directory only if it does not exist

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

25. Reading a file

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

26. Deleting a file

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

27. Appending to a 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 if a file exists

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

29. Send email from a 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 extension

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

35. Count files and 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. 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 for 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 a 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-lineTutorialBashShell 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.