100 Shell Script Examples
100 Shell Script Examples
100 Shell Script Examples
The GNU Bourne-Again Shell also known as bash is the default shell for most of the Linux
distributions. Although bash is commonly run in its interactive form which is the Command Line
Interface (CLI), its non-interactive mode also becomes significant when it comes to executing
Shell Scripts. Scripts are lists of commands stored in a file to run sequentially for task
automation. In this article, you will find 100 shell script examples along with the very basics of
Shell Scripting.
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
assignment operator(=) i.e. VARIABLE_NAME= NEW_VALUE.
● 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"
Output:
My name is Tom. My age is 12.
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
- - (Decrement)
11
Example 4: Calculating the Remainder of a Division using
Bash Script
For generating the remainder of a division use the “%” operator between defined variables.
Code:
#!/bin/bash
num1=30
num2=20
mod=$(($num1%$num2))
echo "The remainder is: $mod"
Output:
The remainder is: 10
12
Example 7: Performing Multiple Mathematical Operations in a
Script
Perform multiple operations using echo without storing the results into another variable.
Code:
#!/bin/bash
read -p "Enter a number:" num1
read -p "Enter a smaller number:" num2
echo "Addition: $(($num1 + $num2))"
echo "Subtraction: $(($num1 - $num2))"
echo "Multiplication: $(($num1 * $num2))"
echo "Division: $(($num1 / $num2))"
Output:
Enter a number:35
Enter a smaller number:15
Addition: 50
Subtraction: 20
Multiplication: 525
Division: 2
13
Conditionals in Shell Scripting
Conditional statements are essential for task automation in shell scripting. A basic conditional
statement in programming language works in such a way that it will execute a piece of code
depending on the fulfillment of some condition. There are four types of conditional statements in
Bash Scripting. Follow the table below to learn about the syntaxes of these conditional
statements.
if if if case expression
[ condition ]; [ condition ]; [ condition1 ]; in
then then then pattern1)
#code #code #code #code;;
fi else elif pattern2)
#code [ condition2 ]; #code;;
fi then *)
#code #code if
else expression
#code doesn't match
fi any patterns;;
esac
14
Example 2: Perform an Arithmetic Operation Based on User
Input
To perform user input based operations implement the if-elif-else condition.
Code:
!/bin/bash
read -p "Enter a number:" num1
read -p "Enter a smaller number:" num2
read -p "Enter an operand:" op
if [ $op == + ]
then
echo "$num1 + $num2 = $((num1+num2))"
elif [ $o == - ]
then
echo "$num1 - $num2 = $((num1-num2))"
elif [ $op == * ]
then
echo "$num1 * $num2 = $((num1*num2))"
elif [ $op == / ]
then
echo "$num1 / $num2 = $((num1/num2))"
else
echo "Operator not listed"
fi
Output:
Enter a number:34
Enter a smaller number:14
Enter an operand:+
34 + 14 = 48
15
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
Example 5: Check if a Given Input is a Valid URL
To check a valid URL use a simple if-else condition with the URL pattern inside the condition.
Code:
#!/bin/bash
read -p "Enter a URL: " url
if [[ $url =~ ^(http|https)://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]
then
echo " This is a valid URL!"
else
echo "This is not a valid URL!"
fi
Output:
Enter a URL: abcdefg1234
This is not a valid URL!
17
#!/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
Output:
Enter a Filename: bin
The directory bin exists.
19
Example 3: Take Two Command Line Arguments and
Calculates their Sum
You can do direct mathematical operations on command line arguments using the $((..)).
Code:
#!/bin/bash
sum=$(( $1 + $2 ))
echo "The sum of $1 and $2 is $sum"
Output:
The sum of 20 and 30 is 50
20
Advanced Bash Scripts
In addition to running basic tasks and commands from the script, you may want to create bash
programs with advanced functionalities. Bash Scripting offers the concepts of string, array, and
loops for achieving such programming goals. In this section, you will learn about these
advanced topics through practical examples.
21
string1="hello"
string2="world"
22
Code:
#!/bin/bash
str="Linuxsimply"
str=$(echo "$str" | rev)
echo "The reversed string: $str"
Output:
The reversed string: ylpmisxuniL
23
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
4
3
2
1
25
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
Enter a number: 6
The factorial of 6 is: 720
27
apple
cherry
orange
28
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
Example 6: Slicing an Array using Bash Script
Slice an array in Bash by placing the indices to slice inside the ${arr[@]:$index1:$index2}
pattern.
Code:
#!/bin/bash
arr=(24 27 84 11 99)
echo "Given array: ${arr[*]}"
read -p "Enter 1st index of slice: " index1
read -p "Enter 2nd index of slice: " index2
sliced_arr=("${arr[@]:$index1:$index2}")
echo "The sliced array: ${sliced_arr[@]}"
Output:
Given array: 24 27 84 11 99
Enter 1st index of slice: 1
Enter 2nd index of slice: 3
The sliced array: 27 84 11
30
Code:
#!/bin/bash
arr=(24 27 84 11 99)
echo "Given array: ${arr[*]}"
len=${#arr[@]}
echo "The length of the array: $len"
Output:
Given array: 24 27 84 11 99
The length of the array: 5
31
if [ "$(echo $s | rev)" == "$str" ]
then
echo "The string is a Palindrome"
else
echo "The string is not a palindrome"
fi
}
read -p "Enter a string: " str
Palindrome "$str"
Output:
Enter a string: wow
The string is a Palindrome
32
Example 3: Convert Fahrenheit to Celsius
Here, the function “Celsius()” runs the necessary formula on the passed temperature value in
Farenheit to convert it into Celsius.
Code:
#!/bin/bash
Celsius () {
f=$1
c=$((($f-32)*5/9))
echo "Temperature in Celsius = $c°C"
}
read -p "Enter temperature in Fahrenheit:" f
Celsius $f
Output:
Enter temperature in Fahrenheit:100
Temperature in Celsius = 37°C
33
Area () {
radius=$1
area=$(echo "scale=2; 3.14 * $radius * $radius" | bc)
echo "Area of a circle with radius $radius is $area."
}
read -p "Enter radius of the circle:" r
Area $r
Output:
Enter radius of the circle:4
Area of a circle with radius 4 is 50.24.
34
Task-Specific Bash Scripts (44 Examples)
In addition to the conceptual bash scripts, in this section, you will find some task-specific script
examples. These scripts are mostly related to the regular process that you run on your system.
Hence, explore the examples below to get more hands-on experience with Shell Scripting.
35
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
4. Copy a File to a New Location
You can copy a file to another location using the bash script below. It will read the filename and
destination path from the terminal and copy the file if it exists in the current directory. If the file is
not there, the script will return an error message.
Code:
#!/bin/bash
read -p "Enter the file name: " file
read -p "Enter destination path:" dest
if [ -e "$file" ]; then
cp $file $dest
file_location=$(readlink -f $dest)
echo "A copy of $file is now located att: $file_location"
else
echo "Error: $file does not exist"
fi
Output:
Enter the file name: poem.txt
Enter destination path:/home/anonnya/Documents
A copy of poem.txt is now located at: /home/anonnya/Documents
37
-----------------------------------
The File text_file1.txt is created!
38
echo "Error! The file $file does not exist."
fi
Output:
Enter the file name for deletion: article1.txt
The file article1.txt deleted successfully!
39
fi
if [ -w "$file" ]; then
echo "Writable"
fi
if [ -x "$file" ]; then
echo "Executable"
fi
else
echo "Error! The file $file does not exist."
fi
Output:
Enter the file name: daffodils.txt
Readable
Writable
40
read -p "Enter the file name: " file
read -p "Enter file owner name: " owner
if [ -f $file ]; then
sudo chown $owner $file
echo "Changed file owner to $owner!"
else
echo "Error! The file $file does not exist."
fi
Output:
Enter the file name: daffodils.txt
Enter file owner name: tom
[sudo] password for anonnya:
Changed file owner to tom!
41
Network Connection Based Shell Scripts
13. Check a Remote Host for its Availability
The following script checks the network status of a remote host. You will need to enter the host
IP address as input and it will return a message saying if the host is up or down.
Code:
#!/bin/bash
read -p "Enter remote host IP address:" ip
ping -c 1 $ip
if [ $? -eq 0 ]
then
echo "-----------------------"
echo "Host is up!"
echo "-----------------------"
else
echo "-----------------------"
echo "Host is down!"
echo "-----------------------"
fi
Output:
Enter remote host IP address:192.168.0.6
PING 192.168.0.6 (192.168.0.6) 56(84) bytes of data.
64 bytes from 192.168.0.6: icmp_seq=1 ttl=64 time=4.10 ms
42
read -p "Enter port number:" PORT
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
Internet connection is up
----------------------------------------------
44
✅Syntax to run the Script: sudo bash bin/adv_example16.sh
Requirement: ifconfig must be installed.
Output:
Enter network configuration variables:
Enter an IP address: 192.168.0.108
Enter a subnet mask: 255.255.255.0
Enter a Gateway address: 192.168.0.1
Enter a DNS address: 8.8.8.8
----------------------------------------------
Network configuration completed
----------------------------------------------
45
read -p "Enter process name: " process
if ! pgrep $process > /dev/null
then
/path/to/process_name &
echo "The Process $process has now started."
else
echo "The Process is already running."
fi
Output:
Enter process name: bash
The Process is already running.
46
pid=$(pgrep -f $process)
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
22. Display the Top 10 CPU-Consuming Processes
The script below lists the top 10 CPU-consuming processes. It prints the Process ID, the
percentage of CPU usage along with the command that runs each process.
Code:
#!/bin/bash
echo "The current top 10 CPU-consuming processes: "
ps -eo pid,%cpu,args | sort -k 2 -r | head -n 11
Output:
The current top 10 CPU-consuming processes:
PID %CPU COMMAND
2161 0.6 /usr/bin/gnome-shell
1126 0.5 /usr/sbin/mysqld
7593 0.5 /usr/libexec/gnome-terminal-server
832 0.2 /usr/bin/java -Djava.awt.headless=true -jar
/usr/share/java/jenkins.war --webroot=/var/cache/jenkins/war --
httpPort=8080
668 0.1 /usr/bin/vmtoolsd
5498 0.1 gjs
/usr/share/gnome-shell/extensions/ding@rastersoft.com/ding.js -E -P
/usr/share/gnome-shell/extensions/ding@rastersoft.com -M 0 -D
0:0:1918:878:1:34:0:0:0:0
104 0.0 [zswap-shrink]
86 0.0 [xenbus_probe]
26 0.0 [writeback]
39 0.0 [watchdogd]
48
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/ding@rastersoft.com/ding.js -E -P
/usr/share/gnome-shell/extensions/ding@rastersoft.com -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
for pid in $(ps -eo pid,%cpu | awk -v t=$threshold '$2 > t {print $1}')
do
kill $pid
done
echo "All processes consuming more than $threshold% CPU killed."
else
echo "There are no process consuming more than $threshold% CPU."
fi
Output:
Enter CPU usage threshold: 10
There are no process consuming more than 10% CPU.
50
System Information Based Shell Scripts
27. Check the Number of Logged-in Users
You view the find the number of logged-in users in your system with the script below. It counts
the users that are logged in only at the current time.
Code:
#!/bin/bash
users=$(who | wc -l)
echo "Number of currently logged-in users: $users"
Output:
Number of currently logged-in users: 2
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
#!/bin/bash
mem=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2}')
echo "Current Memory Usage: $mem"
Output:
Current Memory Usage: 72.48%
52
32. Check the Uptime
The given script can be used to find out the uptime of the system. It will return two values. The
first one is the current time, and the second one is the uptime i.e. for how long the system has
been running. In this example, “up 16:19” indicates that the system has been up for 16 hours
and 19 minutes.
Code:
#!/bin/bash
uptime | awk '{print $1,$2,$3}' | sed 's/,//'
echo "Uptime: $uptime"
Output:
Uptime: 00:16:38 up 16:19
53
Code:
#!/bin/bash
count=$(find / -type f | wc -l)
echo "Number of files in the system: $count."
Output:
Number of files in the system: 500090.
54
Code:
#!/bin/bash
read -p "Enter filename to write alert: " file
touch $file
read -p "Enter disk space threshold: " threshold
df -H | grep -vE "^Filesystem|tmpfs|cdrom" | awk '{ print $5 " " $1 }' |
while read output;
do
usage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
if [ $usage -ge $threshold ]; then
partition=$(echo $output | awk '{ print $2 }')
echo "Alert for \"$partition: Almost out of disk space $usage% as on
$(date) " >> $file
break
fi
done
cat $file
Output:
Enter filename to write alert: alert.log
Enter disk space threshold: 70
Alert for "/dev/sda3: Almost out of disk space 80% as on Thu May 11
01:54:50 AM EDT 2023
mkdir /home/$username/mydir
chown -R $username:$username /home/$username/mydir
usermod -d /home/$username/mydir $username
55
echo "$username ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
Output:
Enter username: Jim
Enter password: linuxsimply
User Jim created successfully!
User Jim added to sudo group!
56
40. Monitor CPU and Memory Usage
The script below can be used to monitor the CPU and Memory usage of a system. It extracts
the CPU and Memory usage information every 10 seconds and converts them into a percentage
for displaying on the screen.
Code:
#!/bin/bash
while true
do
cpu=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" |
awk '{print 100 - $1"%"}')
mem=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
echo "$(date) CPU Usage: $cpu, Memory Usage: $mem"
sleep 10
done
Output:
Sun May 7 02:19:49 AM EDT 2023 CPU Usage: 29.4%, Memory Usage: 68.78%
Sun May 7 02:19:59 AM EDT 2023 CPU Usage: 7.1%, Memory Usage: 68.78%
Sun May 7 02:20:10 AM EDT 2023 CPU Usage: 25%, Memory Usage: 68.72%
Sun May 7 02:20:20 AM EDT 2023 CPU Usage: 17.6%, Memory Usage: 68.72%
Sun May 7 02:20:30 AM EDT 2023 CPU Usage: 6.2%, Memory Usage: 68.70%
read -p "Enter path to the directory containing the command: " comm_path
57
chmod +x $my_comm.sh
58
43. Downloading Files From a List of URLs
The following script takes a filename as input where a list of URLs should be stored. The script
will iterate through the list of URLs and download the available contents on the link. It displays
each download information on the terminal along with the “Completed Download” message.
Upon downloading files from all the URLs, it shows another message saying “All files
downloaded successfully!”.
Code:
#!/bin/bash
read -p "Enter the filename containing URLs: " url_file
while read -r url; do
filename=$(basename "$url")
curl -o "$filename" "$url"
echo "Completed Download $filename"
done < "$url_file"
echo
"--------------------------------------------------------------------------
------------------"
echo "All files downloaded successfully!"
Output:
Enter the filename containing URLs: urls.txt
% 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 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 --:--:-- --:--:-- --:--:--
59
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
;;
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.
Prepared By: Anonnya Ghosh Web View: 100 Shell Script Examples [Free Downloads]
Copyright ©2023 linuxsimply.com| All rights reserved
61
62