Operations 22 min read

40 Simple Yet Effective Linux Shell Script Examples

This article presents 40 practical Bash shell script examples ranging from a basic Hello World program to file management, conditionals, loops, functions, and system maintenance, each illustrated with clear code snippets and step‑by‑step explanations for Linux users.

Linux Tech Enthusiast
Linux Tech Enthusiast
Linux Tech Enthusiast
40 Simple Yet Effective Linux Shell Script Examples

Shells have long been the native command‑line interpreters of Unix‑like systems, and Bash provides powerful scripting capabilities. The following examples demonstrate common tasks and constructs useful for automating daily work on Linux.

1. Hello World

#!/bin/bash

echo "Hello World"

Make the script executable with chmod a+x hello-world.sh and run it via bash hello-world.sh or ./hello-world.sh.

2. Using echo to Print

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

The -e option enables interpretation of escape sequences.

3. Adding Comments

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

The first line is a shebang; lines starting with # are comments.

4. Multi‑line Comments

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

Here a : command with a quoted block acts as a multi‑line comment.

5. while Loop

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

Spaces around the brackets are required.

6. for Loop

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

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

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

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

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

Run as ./test.sh Hey Howdy.

15. Named Arguments

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

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

19. Adding Two Numbers

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

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

Omitting (( )) would cause string concatenation instead of arithmetic.

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 Only 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. 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. Testing File Existence

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

29. Sending Mail from a Script

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

30. Parsing 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

#!/bin/bash
ls -lrt | grep ^- | awk 'END{print $NF}'

34. Batch Add 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 Script

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

All examples are self‑contained Bash scripts that can be copied, saved with a .sh extension, made executable, and run on any Linux system.

Command Linebashshell scriptingscripts
Linux Tech Enthusiast
Written by

Linux Tech Enthusiast

Focused on sharing practical Linux technology content, covering Linux fundamentals, applications, tools, as well as databases, operating systems, network security, and other technical knowledge.

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.