100-shell-script-examples-by-SAN MASTERS
100-shell-script-examples-by-SAN MASTERS
100-shell-script-examples-by-SAN MASTERS
2/11/2024
Table of Contents
1
The syntax for Conditional Statements in Shell Scripting.......................................... 14
Example 1: Check if a Number is an Even or Odd.................................................... 14
Example 2: Perform an Arithmetic Operation Based on User Input...........................15
Example 3: Performs a Logical Operation Based on User Input............................... 15
Example 4: Check if a Given Input is a Valid Email ID...............................................16
Example 5: Check if a Given Input is a Valid URL..................................................... 17
Example 6: Check if a Given Number is Positive or Negative................................... 17
Example 7: Check if a File is Writable........................................................................18
Example 8: Check if a File Exists or Not.................................................................... 18
Example 9: Check if a Directory Exists or Not........................................................... 18
Miscellaneous Bash Scripts............................................................................................. 19
Example 1: Echo with New Line................................................................................ 19
Example 2: Changing Internal Field Separator(IFS)/Delimiter...................................19
Example 3: Take Two Command Line Arguments and Calculates their Sum............20
Example 4: Take Password Input...............................................................................20
Example 5: Take Timed Input.....................................................................................20
Advanced Bash Scripts......................................................................................................... .21
Strings in Shell Scripting.................................................................................................. 21
Example 1: Find the Length of a String......................................................................21
Example 2: Check if Two Strings are Equal...............................................................22
Example 3: Convert All Uppercase Letters in a String to Lowercase........................ 22
Example 4: Remove All Whitespace from a String.................................................... 22
Example 5: Reverse a String..................................................................................... 23
Example 6: Reverse a Sentence............................................................................... 23
Example 7: Capitalize the First Letter of a Word........................................................23
Example 8: Replace a Word in a Sentence.............................................................. 24
Loops in Shell Scripting................................................................................................... 24
Syntaxes for Loops in Bash Scripting:....................................................................... 24
Example 1: Print Numbers from 5 to 1....................................................................... 24
Example 2: Print Even Numbers from 1 to 10............................................................25
Example 3: Print the Multiplication Table of a Number.............................................. 25
Example 4: Calculate the Sum of Digits of a Given Number..................................... 26
Example 5: Calculate the Factorial of a Number....................................................... 26
Example 6: Calculate the Sum of the First “n” Numbers............................................27
Arrays in Shell Scripting.................................................................................................. .27
Example 1: Loop Through Array Elements................................................................ 27
Example 2: Find the Smallest and Largest Elements in an Array..............................28
Example 3: Sort an Array of Integers in Ascending Order......................................... 29
Example 4: Remove an Element from an Array.........................................................29
Example 5: Inserting an Element Into an Array......................................................... 29
Example 6: Slicing an Array using Bash Script..........................................................30
2
Example 7: Calculate the Average of an Array of Numbers...................................... 30
Example 8: Find the Length of an Array.................................................................... 31
Functions in Shell Scripting............................................................................................. .31
Example 1: Check if a String is a Palindrome............................................................32
Example 2: Check if a Number is Prime.................................................................... 32
Example 3: Convert Fahrenheit to Celsius................................................................ 33
Example 4: Calculate the Area of a Rectangle.......................................................... 33
Example 5: Calculate the Area of a Circle................................................................. 34
Example 6: Grading System...................................................................................... 34
Task-Specific Bash Scripts (44 Examples)............................................................................ 35
Regular Expression Based Scripts.................................................................................. 35
1. Search for a Pattern inside a File...........................................................................35
2. Replace a Pattern in a Fille....................................................................................36
File Operations with Shell Scripts.................................................................................... 36
3. Take Multiple Filenames and Prints their Contents................................................36
4. Copy a File to a New Location............................................................................... 37
5. Create a New File and Write Text Inside................................................................37
6. Compare the Contents of Two Given Files............................................................ 38
7. Delete a Given File If It Exists................................................................................ 39
8. Renames a File from Script................................................................................... 39
File Permission Based Shell Scripts................................................................................ 40
9. Check the Permissions of a file..............................................................................40
10. Sets the Permissions of a Directory for the Owner.............................................. 40
11. Change the File Owner........................................................................................ 41
12. Change the Overall Permissions of a File............................................................41
Network Connection Based Shell Scripts........................................................................ 42
13. Check a Remote Host for its Availability.............................................................. 42
14. Test if a Remote Port is Open.............................................................................. 43
15. Checking Network Connectivity........................................................................... 43
16. Automating Network Configuration...................................................................... 44
17. Process Management: Check if a Process is Running........................................ 45
Process Management Based Shell Scripts......................................................................46
18. Start a Process if It's Not Already Running.......................................................... 46
19. Stop a Running Process...................................................................................... 46
20. Restart a Runnimg process................................................................................. 47
21. Monitor a Process and Restart It If Crashes........................................................ 47
22. Display the Top 10 CPU-Consuming Processes..................................................48
23. Display the Top 10 Memory-Consuming Processes............................................ 49
24. Kill Processes of a Specific User......................................................................... 49
25. Kill All Processes That are Consuming More Than a Certain Amount of CPU....50
26. Kill All Processes That are Consuming More Than a Certain Amount of Memory..
3
50
System Information Based Shell Scripts..........................................................................51
27. Check the Number of Logged-in Users................................................................51
28. Check the Operating System Information............................................................ 51
29. Check the System’s Memory Usage.................................................................... 52
30. Check the System’s Disk Usage.......................................................................... 52
31. Check the System’s Network Information............................................................ 52
32. Check the Uptime................................................................................................ 53
33. Check the System Load Average.........................................................................53
34. Check the System Architecture............................................................................53
35. Count the Number of Files in The System........................................................... 54
Advanced Tasks with Shell Scripts.................................................................................. 54
36. Automated Backup.............................................................................................. .54
37. Generate Alert if Disk Space Usage Goes Over a Threshold..............................55
38. Create a New User and Add to Sudo Group........................................................55
39. Monitor Network traffic......................................................................................... 56
40. Monitor CPU and Memory Usage........................................................................ 57
41. Creating a Script and Adding It to PATH.............................................................. 57
42. Running a Command at Regular Intervals...........................................................58
43. Downloading Files From a List of URLs...............................................................59
44. Organizes Files in a Directory Based on Their File Types................................... 60
Conclusion............................................................................................................................. 61
4
NOTE: You must write the SheBang(#!) on the very first line of the Script.
💡 NOTE: You can skip this step if the directory is already created.
➌ After that, create a bash script file inside the bin directory with the command below.
nano bin/hello_world.sh
Explanation:
● nano: Creates/edits text files with Nano text editor.
● hello_world.sh: File for writing the bash script.
❹ Now, write the following script in hello_world.sh file.
#!/bin/bash
echo "Hello World"
5
❺ To save and exit from the script, press CTRL+S and CTRL+X respectively.
❻ Now, Type the following to make the script executable for the current user in your system.
chmod u+rwx bin/hello_world.sh
Explanation
● chmod: Changes folder permissions.
● u+rwx: Adds read, write, and execute permissions for the current user.
● hello_world.sh: the bash script file.
❼ Finally, restart your system to add the newly created bin directory to the $PATH variable
by typing the command below.
reboot
Restarting the system by default runs the .profile script which adds the user’s private bin
directory to $PATH and makes the files inside the bin directory accessible for every shell
session.
6
Step 2: Running the “Hello World” Bash Script in Linux
After restarting the system you will be able to run the “hello_world.sh” script from any path
under the current user account. To learn how you can execute the script follow the steps
below. Steps to follow:
➊ At first, press CTRL+ALT+T to open the Ubuntu
Terminal.
➋ Run the previously written script by simply typing the file name and hitting ENTER.
bash hello_world.sh
In the above image, you can see that, I successfully ran the created “hello_world.sh” script.
The “Hello World” message is displayed on the terminal from that script.
7
● No need to define variable type while declaring variables.
● Enclose multiple words or string values within Single Quote (' ') to consider all
characters as input.
8
#!/bin/bash
read -p "Enter a number:" num
echo "The number is: $num"
Output:
#!/bin/bash
read -p "Enter a number:" num
echo "The number is: $num"
9
Example 6: Print Environment Variable using Bash Script
You can store an Environment Variable in a regular manner and print it using ${!..}
syntax.
Code:
#!/bin/bash
read -p "Enter an Environment Variable name:" var
echo "Environment:${!var}"
Output:
Enter an Environment Variable name:
HOME
Environment:/home/anonnya
10
equal) shift)
- - (Decrement)
11
The division is: 6
12
Enter minimum range:10
Enter maximum range:35
Random Number: 24
13
Output:
Enter two numbers: 4 5
Enter operation to perform (AND, OR, NOT): AND
Result: 4 & 5 = 4
14
Enter a number:25
The number is odd
15
read -p "Enter an operation(and/or/not) to perform:" op
case $op in
and)
if [[ $val1 == true && $val2 == true ]]
then
echo "Result: true"
else
echo "Result: false"
fi;;
or)
if [[ $val1 == true || $val2 == true ]]
then
echo "Result: true"
else
echo "Result: false"
fi;;
not)
if [[ $val1 == true ]]
then
echo "Result: false"
else
echo "Result: true"
fi;;
*) echo "Invalid operator."
esac
Output:
Enter two values: true false
Enter an operation(and/or/not) to perform:or
Result: true
16
fi
Output:
Enter an email ID: [email protected]
17
Example 7: Check if a File is Writable
You can verify file permissions inside if-else condition. For this, the write permission is checked
with the -w notation.
Code:
#!/bin/bash
read -p "Enter a File Name:" fname
if [ -w $fname ]
then
echo "The File $fname is writable."
else
echo "The File $fname is not writable."
fi
Output:
Enter a File Name:file1.txt
The File file1.txt is writable.
18
then
echo "The directory $dir does not exist!"
exit 1
fi
echo "The directory $dir exists."
Output:
Enter a Filename: bin
The directory bin exists.
19
Output:
1st value: 5
2nd value: 60
3rd value: 70
20
Enter your name within 5 seconds: Anonnya
21
Example 2: Check if Two Strings are Equal
Check whether two strings are same or not using the == (Equal) operator inside if condition.
Code:
#!/bin/bash
string1="hello"
string2="world"
22
The resultant string: HellofromLinuxsimply!!
23
Example 8: Replace a Word in a Sentence
You can replace the first occurrence of a word in a string with a given word using the $(../../..).
Code:
#!/bin/bash
read -p "Enter a sentence: " str1
read -p "Enter the word to be replaced: " str2
read -p "Enter the new word: " str3
echo "Modified sentence: ${str1/$str2/$str3}"
Output:
Enter a sentence: I love Linux
Enter the word to be replaced: Linux
Enter the new word: Linuxsimply
Modified sentence: I love Linuxsimply
24
do
echo $n
n=$((n-1))
done
Output:
5
4
3
2
1
25
echo "$num x $i = $((num*i))"
done
Output:
Enter a number: 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
26
temp=1
for (( i=1; i<=$num; i++ ))
do
temp=$((temp*i))
done
echo "The factorial of $num is: $temp"
Output:
Enter a number: 6
The factorial of 6 is: 720
27
arr=("mango" "grape" "apple" "cherry" "orange")
for item in "${arr[@]}"; do
echo $item
done
Output:
mango
grape
apple
cherry
orange
28
Example 3: Sort an Array of Integers in Ascending Order
You can sort an array of integers by converting it into a list of integers using “tr ‘\n’”. The list of
integers is sorted with the “sort -n” command and then converted back into an array.
Code:
#!/bin/bash
arr=(24 27 84 11 99)
echo "Given array: ${arr[*]}"
arr=($(echo "${arr[*]}" | tr ' ' '\n' | sort -n | tr '\n' ' '))
echo "Sorted array: ${arr[*]}"
Output:
Given array: 24 27 84 11 99
Sorted array: 11 24 27 84 99
29
arr=("${arr[@]:0:$index}" "$new_val" "${arr[@]:$index}")
echo "The updated array: ${arr[@]}"
Output:
Given array: 24 27 84 11 99
Enter an element to insert: 100
Enter the index to insert the element: 3
The updated array: 24 27 84 100 11 99
30
echo "Average of the array elements: $avg"
Output:
Enter an array of numbers (separated by space):
23 45 11 99 100
Average of the array elements: 55
31
● To access arguments inside the function, use $1, $2, $3 … and so on according to the
number and sequence of arguments passed.
● The scope of the variables declared inside a function remains within the function.
32
echo "The number $num is Not Prime"
return
fi
done
echo "The number $num is Prime"
}
read -p "Enter a number: " num
Prime "$num"
Output:
Enter a number: 2
The number 2 is Prime
33
}
read -p "Enter height and width of the ractangle:" h w
Area $h $w
Output:
Enter height and width of the ractangle:10 4
"Area of the rectangle is: 40"
34
grade="D"
else
grade="F"
fi
echo "The grade for mark $s is $grade"
}
read -p "Enter a score between 1-100:" s
Grade $s
Output:
Enter a score between 1-100:76
"The grade for mark 76 is A"
35
2. Replace a Pattern in a Fille
The following script will take a file name and a pattern from the user to replace it with a new
pattern. Finally, it will display the updated lines on the terminal. If the pattern to replace does not
exist, then it will show an error message.
Code:
#!/bin/bash
read -p "Enter filename: " filename
read -p "Enter a pattern to replace: " pattern
read -p "Enter new pattern: " new_pattern
grep -q $pattern $filename
if [ $? -eq 0 ]; then
sed -i "s/$pattern/$new_pattern/g" $filename
echo "Updated Lines: "
grep -w -n $new_pattern $filename
else
echo "Error! Pattern did not match."
fi
Output:
Enter filename: poem.txt
Enter a pattern to replace: daffodils
Enter new pattern: dandelions
Updated Lines:
4:A host, of golden dandelions;
27:And dances with the dandelions.
36
cat "$file"
else
echo "Error: $file does not exist"
fi
done
Output:
Enter the file names: message.txt passage.txt
Contents of message.txt:
"Merry Christmas! May your happiness be large and your bills be small."
Contents of passage.txt:
The students told the headmaster that they wanted to celebrate the victory
of the National Debate Competition.
37
#!/bin/bash
read -p "Enter the file name: " file
echo "Enter text to write:"
read text
echo "$text" > "$file"
echo "-----------------------------------"
echo "The File $file is created!"
Output:
Enter the file name: text_file1.txt
Enter text to write:
In English, there are three articles: a, an, and the. Articles are used
before nouns or noun equivalents and are a type of adjective. The definite
article (the) is used before a noun to indicate that the identity of the
noun is known to the reader.
-----------------------------------
The File text_file1.txt is created!
38
The Files article1.txt and text_file1.txt are identical.
39
The file poem.txt has been renamed as daffodils.txt!
40
echo "Directory permissions have been updated!"
else
echo "Error! The directory $dir does not exist."
fi
Output:
Enter the directory name: Documents
Directory permissions have been updated!
41
sudo chmod $permissions $file
echo "Permissions for the file $file has been changed!"
else
echo "Error! The file $file does not exist."
fi
Output:
Enter the file name: daffodils.txt
Enter new permissions in Absolute Mode: 777
[sudo] password for anonnya:
Permissions for the file daffodils.txt has been changed!
42
Host is up!
-----------------------
if [ $? -eq 0 ]; then
echo "----------------------------------------------"
echo "Port $PORT on $HOST is open"
echo "----------------------------------------------"
else
echo "----------------------------------------------"
echo "Port $PORT on $HOST is closed"
echo "----------------------------------------------"
fi
Output:
Enter host address:192.168.0.107
Enter port number:80
Connection to 192.168.0.107 80 port [tcp/http-alt] succeeded!
----------------------------------------------
Port 80 on 192.168.0.107 is open
----------------------------------------------
43
if ping -q -c 1 -W 1 $HOST >/dev/null; then
echo "----------------------------------------------"
echo "Internet connection is up"
echo "----------------------------------------------"
else
echo "----------------------------------------------"
echo "Internet connection is down"
echo "----------------------------------------------"
fi
Output:
Enter a host address:192.168.0.107
----------------------------------------------
Internet connection is up
----------------------------------------------
44
echo "----------------------------------------------"
else
echo "----------------------------------------------"
echo "Error while setting the DNS server."
fi
else
echo "----------------------------------------------"
echo "Error while setting the default gateway."
fi
else
echo "----------------------------------------------"
echo "Network Configuration Failed."
fi
45
Enter process name: bash
Process is running.
46
Enter process name: nslookup
The Process nslookup has stopped.
if [ -n "$pid" ]; then
kill $pid
sleep 5
if pgrep -f $process> /dev/null; then
echo "Process did not exit properly, force killing..."
kill -9 $pid
fi
fi
process_path=$(which $process)
$process_path & echo "Process restarted."
Output:
Enter process name: firefox
Process restarted.
47
echo "The Process $process is running."
sleep 5
else
$process_path &
echo "The Process $process restarted."
continue
fi
done
Output:
Enter process name: firefox
The Process firefox is running.
The Process firefox is running.
48
23. Display the Top 10 Memory-Consuming Processes
The given script lists the top 10 memory-consuming processes. It prints the Process ID,
percentage of memory usage as well as the commands for running each process.
Code:
#!/bin/bash
echo "The current top 10 Memory-consuming processes: "
ps -eo pid,%mem,args | sort -k 2 -r | head -n 11
Output:
The current top 10 Memory-consuming processes:
PID %MEM COMMAND
1126 9.7 /usr/sbin/mysqld
832 6.8 /usr/bin/java -Djava.awt.headless=true -jar
/usr/share/java/jenkins.war --webroot=/var/cache/jenkins/war
--httpPort=8080
2161 6.7 /usr/bin/gnome-shell
2516 2.1 /usr/bin/Xwayland :0 -rootless -noreset -accessx -core -auth
/run/user/1000/.mutter-Xwaylandauth.G8UR41 -listen 4 -listen 5 -displayfd 6
-initfd 7
2585 1.9 /usr/libexec/gsd-xsettings
1209 1.5 /usr/bin/dockerd -H fd://
--containerd=/run/containerd/containerd.sock
5498 1.5 gjs
/usr/share/gnome-shell/extensions/[email protected]/ding.js -E -P
/usr/share/gnome-shell/extensions/[email protected] -M 0 -D
0:0:1918:878:1:34:0:0:0:0
2966 1.4 /usr/bin/gedit --gapplication-service
7593 1.3 /usr/libexec/gnome-terminal-server
2381 1.3 /usr/libexec/evolution-data-server/evolution-alarm-notify
49
Enter username: tom
[sudo] password for anonnya:
All processes of user tom have been terminated.
50
kill $pid
done
echo "All processes consuming more than $threshold KB memory killed."
else
echo "There are no process consuming more than $threshold KB memory."
fi
Output:
Enter memory usage threshold (in KB): 10
There are no process consuming more than 10 KB memory.
os_name=$(uname -s)
os_release=$(uname -r)
os_version=$(cat /etc/*-release | grep VERSION_ID | cut -d '"' -f 2)
os_arch=$(uname -m)
51
Output:
OS Name: Linux
OS Release: 5.19.0-38-generic
OS Version: 22.04
OS Architecture: x86_64
52
gw=$(ip route | awk '/default/ { print $3 }')
echo "Gateway: $gw"
dns=$(grep "nameserver" /etc/resolv.conf | awk '{print $2}')
echo "DNS Server: $dns"
Output:
System's network information:-
IP Address: 192.168.0.109
Gateway: 192.168.0.1
DNS Server: 127.0.0.53
53
#!/bin/bash
arch=$(uname -m)
echo "System Architecture: $arch"
Output:
System Architecture: x86_64
54
Enter path of the directory to backup: /home/anonnya/Documents
Enter destination path for backup: /home/anonnya/Desktop
tar: Removing leading `/' from member names
Completed Creating backup at: /home/anonnya/Desktop.
55
#!/bin/bash
mkdir /home/$username/mydir
chown -R $username:$username /home/$username/mydir
usermod -d /home/$username/mydir $username
56
echo "$(date) RX: $rx, TX: $tx"
sleep 10
done
Output:
Enter network interface to monitor traffic (ex. eth0): ens33
Wed May 10 16:55:40 +06 2023 RX: 342(40.4KB), TX: 171(18.4KB)
Wed May 10 16:55:51 +06 2023 RX: 355(41.6KB), TX: 178(19.0KB)
Wed May 10 16:56:01 +06 2023 RX: 361(42.0KB), TX: 178(19.0KB)
Wed May 10 16:56:11 +06 2023 RX: 361(42.0KB), TX: 178(19.0KB)
57
#!/bin/bash
read -p "Enter a name for the command: " my_comm
echo "Enter commands to write on script:"
read comm
read -p "Enter path to the directory containing the command: " comm_path
58
# Add command to crontab
(crontab -l ; echo "$interval $command_to_run") | sort - | uniq - | crontab
-
echo "Command added to crontab and will run at $interval"
Output:
Enter command to run: echo "1 Minute passed!" >> time.log
Enter interval for running the command (m h dom mon dow): * * * * *
Command added to crontab and will run at * * * * *
59
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:--
0curl: (6) Could not resolve host: linuxsimply.com
Completed Download Emacs-Keybindings-or-Shortcuts-in-Linux.pdf
curl: (3) URL using bad/illegal format or missing URL
Downloaded
% Total % Received % Xferd Average Speed Time Time Time
Current
Dload Upload Total Spent Left
Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:--
0curl: (6) Could not resolve host: linuxsimply.com
Completed Download Bash-Terminal-Keyboard-Shortcuts-for-Information.pdf
---------------------------------------------------------------------------
-----------------
All files downloaded successfully!
This script will create five directories: 1) Documents, 2) Images, 3) Music, 4) Videos, and 5)
Others only if they do not already exist on the destination path. Then, it will check all the files
and their extension and move them to the corresponding directory. If there is any unknown file
extension, then the script will move the file to the Others Directory.
Code:
#!/bin/bash
60
extension="${file##*.}"
case "${extension}" in
txt|pdf|doc|docx|odt|rtf)
mv "${file}" "${dest_dir}/Documents"
;;
jpg|jpeg|png|gif|bmp)
mv "${file}" "${dest_dir}/Images"
;;
mp3|wav|ogg|flac)
mv "${file}" "${dest_dir}/Music"
;;
mp4|avi|wmv|mkv|mov)
mv "${file}" "${dest_dir}/Videos"
;;
*)
mv "${file}" "${dest_dir}/Others"
;;
esac
fi
done
echo "Files organized successfully!"
Output:
Enter path to the source directory: /home/anonnya/Downloads
Enter path to the destination directory: /home/anonnya/Downloads_Organized
Files organized successfully!
Conclusion
This article covers 100 shell script examples that a user can frequently use. These examples
range from basic to advanced topics along with the preliminary concepts of script writing
and configurations. Furthermore, the examples are divided into sections and subsections
depending on their topic and level of understanding. Therefore, it is a proper guide for users of
every category.
61