Example of 20 Bash Script

Example of 20 Bash Script

bash script

This guide is designed to provide a comprehensive overview of shell scripting, focusing on bash and its fundamental concepts and syntax. The aim is to equip you with the knowledge to script in bash proficiently and automate tasks efficiently on Linux systems.

Throughout this guide, you’ll delve into essential topics such as variables, conditional statements, handling command line arguments in scripts, user input processing, loops, functions, and various other key scripting elements. The content is structured to facilitate a step-by-step learning approach, making it accessible for those seeking to build a solid foundation in bash scripting.

Jump To...

What constitutes shell/bash scripting?

Bash scripting serves as a robust tool for automating operations on a Linux system. From leveraging the exit status of shell commands to directing script flow with if-elseif-else statements, bash scripts empower users to utilize command-line capabilities for intricate tasks.

File permissions ensure restricted access to sensitive information, allowing only valid users to interact. The bash read command facilitates user input within a script, enhancing its interactivity.

Moreover, the capacity to store and manipulate string variables grants bash scripting a flexibility akin to other programming languages.

Whether automating straightforward tasks or crafting intricate scripts, proficiency in bash scripting is a vital asset for Linux system administrators.

A collection of executable commands is referred to as a shell script or a bash script. These files carry the extension “.sh.”

Which shell implementations are available?

bsh – Bourne shell, named after Stephen Bourne.

Bash – Bourne Again Shell, an enhanced version of bash and the default shell for most UNIX-like systems.

Other shell programs include C shell, Korn shell, and more.

Bash is both a command line bash interpreter and a comprehensive programming language for scripting. In this guide, we will delve into writing shell scripts using bash syntax, featuring twenty (20) bash script examples.

What is the process of crafting a shell script?

Initially, create a shell script in your terminal using the ‘touch script.sh’ command. You have the flexibility to choose any name for the file, but it’s customary for shell script files to end with the “.sh” extension.

bash script 1

Guidelines for Script Composition

At the start of each script, it’s important to specify which type of shell should execute it. This initial line in the script is referred to as the ‘shebang line.’ Below are the shebang lines for the Bourne shell, Bourne Again Shell, and C shell.

  • SH – #!/bin/sh

  • BASH – #!/bin/bash

  • ZSH – #!/bin/zsh

The term ‘shebang’ is derived from the “#” and “! ” symbols, often referred to as ‘sharp’ and ‘bang,’ respectively. The combination of sharp and bang results in ‘shebang.’

Access and Modify the Script File

You can utilize any text editor to open and modify the script file you generated. For instance, you can use commands like ‘vim script.sh’ or ‘nano script.sh’ to open the file with the Vim editor or Nano editor.

bash script 2

Initially, we need to compose the shebang line, indicating the shell command program the operating system should use to execute the subsequent command lines. Afterward, we can write our initial script line to display a message, such as ‘echo “Hello world!”‘.

To start writing in the Vim editor, press ‘i’ for ‘INSERT’ mode. Once your script file is finished, press the ‘Esc’ key and type ‘:wq’ to write changes and quit the Vim editor.

bash script 3

Grant Permissions to Your Script File

Next, you need to grant execute permission to that file. It’s likely that you don’t have permission to execute the script.sh file, even as the file owner.

You can verify permissions using the ‘ls –l script.sh’ command. If you lack execution permission, you can obtain it by running the ‘sudo chmod u+x script.sh’ command.

Upon rerunning the ‘ls –l script.sh’ command, you’ll observe that executable permissions have been added, and the color of the file name has changed, indicating that it is now an executable file.

bash script 4

Execution of the Script

Lastly, you can execute the ‘chmod +x script.sh’ command or ‘bash script.sh’ command to run the script. Your output will resemble the following.

bash script 5

20 Illustrations for a Deeper Exploration into Bash Scripting

Now that you have a fundamental understanding, let’s delve into bash script examples to enhance your knowledge.

Sample 01 – Incorporating Variables in Scripting

In this initial bash script example, we’ll explore how to employ variables in scripts. Bash shell scripts offer flexibility in handling variables. Let’s create a script involving two variables: “name” and “place.”

Then we can assign a person and place names to the two variables and output them in an echo command statement. You can write a similar script, as follows, and save and run the script on the bash command line.
 
#!/bin/bash
echo "use of variables in scripts"
echo "==========================="
name="jhon"
place="DC"
echo "$name lives in $place"

 

You will get an output as shown in the image below.

Sample 02 – Input and Results

At present, it’s evident that we have the capability to display strings on the terminal as output. Moreover, we can retrieve input from the terminal.

In this instance, we will accomplish this by prompting the user for a name via the terminal. The ensuing code snippet is designed to execute this task. We employ ‘echo’ statements to display strings and include blank lines within the code.

Additionally, we utilize the ‘read’ keyword along with a variable to capture the provided name from the terminal

#!/bin/bash
echo "Inputs and outputs"
echo "Hi, Im jhon, What is your name ?"
read name
echo "Nice to meet you $name!"
echo "* end of script *"

Here is the script’s generated output.

bash script 6

Sample 03 - Conditional statements with IF

In this scenario, we employ a straightforward ‘if statement’ to verify the existence of a file. The syntax of a bash ‘if statement’ is easily comprehensible, resembling that of a typical programming language.

The sole distinction lies in the utilization of the ‘fi’ keyword, serving as an indicator for the conclusion of the conditional statements. Let’s explore the following bash script to illustrate this concept.

#!/bin/bash
echo if then else statements
echo
file=abc.txt
if [ -e $file ]
then
echo "Yey, File exists!"
else
echo "file does not exist"
echo "creating the file..".
touch $file
fi
echo "* end of script *"

The output may look similar to the below image.

bash script 7

Sample 04 – Case statements

In the context of this bash program, user options are presented along with corresponding identifiers. Each option is associated with a specific command.

Upon user selection of an option, the program executes the corresponding command. In this instance, the ‘uptime’ and ‘date’ commands are employed for the available options.

#!/bin/bash
echo "choose an option:"
echo "1 - system uptime"
echo "2 - date and time"
echo
read choice
case $choice in
1) uptime;;
2) date;;
*) invalid argument
esac
echo
echo "* end of script *"

We should utilize the ‘esac’ keyword to signify the conclusion of the case.

The resulting output is as follows.

bash script 8

Sample 05 – For loop

In this example, we’ll employ a “for loop” to display a particular string a specified number of times. You should find the following code example easy to understand.

#!/bin/bash
echo "For loop example"
for i in 1 2 3 4 5
do
echo "$i - Welcome"
done
echo "* end of script *"

Output:

Sample 06 – Do while

Employing a “do while” loop in bash scripting is straightforward. In this context, the ‘-le’ keywords signify the “less than or equal” comparison operator commonly found in typical programming languages.

The script below will continue to execute until the variable’s value exceeds five.

bash script 9

#!/bin/bash
echo "Do while loop example"
a=1
while [ $a -le 5 ]
do
echo "Hi - Im number $a"
(( a++ ))
done
echo "* End of Script *"

Once you run the script, your output may look the same as the following.

bash script 10

Sample 07 – Access data from a file

Typically, the “cat” command is employed to read files, and it can also be utilized within a script file. Begin by creating an empty file named abc.txt.

Here, we attempt to read the empty file “abc.txt” using the command “cat abc.txt.”

Next, retrieve the command execution history and redirect the output to the txt file. Finally, incorporate the cat command within our script for testing purposes.

#!/bin/bash cat abc.txt

Output

bash script 11

Sample 08 – Check remote server connection

In this script, the initial step involves prompting the user to enter an IP address, or alternatively, a default value such as “google.com” is provided. Subsequently, the script reads the user input and incorporates it into the “ping” command.

Once the “ping” command is executed with the provided input, the script captures the output from the ping operation. This output is then displayed, providing the user with information about the results of the ping command for the specified destination.

Following the execution of the ‘ping –c2 $ip’ command, which instructs the system to ping the specified destination twice, the script evaluates the exit status of the ping command. As a convention, an exit status of 0 signifies success in the ping command.

In the script, if the exit status is “0,” indicating a successful ping, a corresponding “success” message is displayed. Conversely, if the exit status is non-zero, suggesting an unsuccessful ping, the script outputs a “try again” message. This way, the script provides a clear indication to the user about the outcome of the ping operation for the specified destination.

#!/bin/bash
echo "Enter an ip address to ping test :"
read ip
echo "you gave - $ip"
echo "pinging > +++++++++++++++++++++++++++++++"
ping -c2 $ip
if [ $? -eq 0 ]
then
echo
echo "=============================================="
echo "Ping success!"
else
echo "----------------------------------------------"
echo "Ping not success!, try again.."
fi
echo
echo "* end of script *"

Below is the output.

bash script 12

Sample 09 – Delete old files

A script can be crafted to delete outdated files by assessing their age and removing them from a designated location.

Suppose we intend to eliminate files that are older than 90 days. If there are no existing older files, you can generate them using the following command: `touch -d “Fri, 2 September 2022 12:30:00” file1`.

The file named file1, established on September 2nd, 2022, can then be removed using the command: `find /home/test/scripts -mtime +90 -exec rm {} \;`. This command identifies files in the specified directory (`/home/test/scripts`) that surpass the 90-day age threshold and subsequently executes the `rm` (remove) command on each of them.

Moreover, if desired, you can employ the command ‘find /home/test/scripts -mtime +90 -exec ls -l {} \;’ to locate and list files that exceed the 90-day age threshold.

#!/bin/bash
find /home/test/scripts/ -mtime +90 -exec rm {} \;

Output:

bash script 12

Sample 10 – Backup file system

In the given script, we’ll generate a backup of the ‘backup’ directory using tar. Subsequently, we’ll employ gzip to compress the backup file, transforming “scripts-backup.tar” into ‘scripts-backup.tar.gz’. To conclude, a message will be displayed indicating the completion of the process.

#!/bin/bash
tar cvf /home/test/scripts/scripts-backup.tar /home/test/scripts/backup
gzip scripts-backup.tar
echo "process finished!"

The depicted illustrations showcase the directory structure before and after the execution of the script file.

Before:

bash script 14

After:

bash script 15

Sample 11 – Sleep

In this scenario, the sleep command is employed to initiate the system’s sleep mode. By defining a specific sleep time, we can observe its functionality.

The sleep command effectively halts the ongoing process, inducing the system to enter a sleep state. Let’s experiment with it now. In this instance, the sleep command is utilized within a ‘for loop,’ delivering a pleasant evening message every 20 seconds.

#!/bin/bash
echo "For loop with sleep timer"
for i in 1 2 3 4 5
do
echo "Im going to sleep - day $i" && sleep 20
done
echo "* end of script *"

Output

bash script 17

Sample 12 – Array

A Bash array serves as a data structure for organizing and storing information with an index. It proves beneficial for managing data that needs to be accessed in various ways.

These arrays excel at storing diverse elements, including both strings and numbers. In the following example, we are working with an array that holds information about students. We’ll iterate through the array using a “for loop” to read each element one by one.

#!/bin/bash
students=(jessica jhon dwain sian rose mary jake123 sam303)
echo "Read data from an array"
for i in "${students[@]}"
do
echo "Student name : $i"
done
echo "* end of script *"

Output

bash script 19

Sample 13 – Bash functions

Functions in bash scripts are constructed similarly to those in conventional programming languages, allowing us to integrate them seamlessly into script files.

In this example, an array of visitors is employed, and a personalized greeting is extended to each guest. By using the defined bash function within a script, we can conveniently invoke it by name whenever needed.

#!/bin/bash
welcome () {
guests=(jessica jhon dwain sian rose mary jake123 sam303)
echo "Write an array inside a Function"
for i in "${guests[@]}"
do
echo "Welcome $i as a guest!"
done
}
welcome

Output

bash script 20

Sample 14 – Concatenate Strings

String concatenation involves appending one string to another. To achieve this, we utilize a fourth variable to concatenate three string variables.

Ultimately, we can display the concatenated string as the output.

#!/bin/bash
beginning="Jhon "
middle="was born in"
end=" USA"
apendedvalue="$beginning$middle$end"
echo "$apendedvalue"

Output

bash script 23

Sample 15 – Length of a string

In this uncomplicated example, we can create a script file to obtain the output. A sentence is assigned to a variable, and the script calculates and displays the length of the sentence.

#!/bin/bash
echo "Below is the sentence"
echo "+++++++++++++++++++++++"
echo
echo "how long is this sentence?"
echo
sentence="how long is this sentence?"
length=${#sentence}
echo "Length of the sentence is :- $length"

Output

bash script 24

Sample 16 – Find and replace a string

This bash script showcases the capability to find and replace a string in a file using shell scripting. It enables easy manipulation of a file, empowering users to locate and replace strings as required.

Upon execution, the script generates a new bash file, replacing the specified string with a new one to ensure that the information in the file remains current and accurate.

This script proves to be a valuable tool for users involved in file modifications, particularly those overseeing a substantial number of files or a dynamic process.

Crafted in bash, the script is designed to function either as a standalone bash file or seamlessly integrated into a larger script.

The incorporation of shell scripting in this example ensures a user-friendly experience, enabling quick and easy manipulation of files, streamlining the process of finding and replacing strings.

Whether dealing with a single file or overseeing a complex system, this script serves as a testament to the formidable power and versatility inherent in bash scripting.

#!/bin/bash
echo "please enter a string"
read input
echo "Enter the word you need to replace -"
read rep
echo "enter the replacement"
read replacement
echo
echo "Replaced sentence - ${input/$rep/"$replacement"}"

Below is the output.

bash script 25

Sample 17 – Check the existence of a file

The script presented below showcases the capability to verify the existence of a file on a system using the command line. User input, in the form of a string value representing the file name to be checked, is processed by the script.

Utilizing the “test” command, the script efficiently determines the file’s existence. The output provides a clear message indicating the result of the check. This script is designed to run autonomously as a standalone sh file or be seamlessly integrated into a larger bash script.

Despite its simplicity, this robust bash file exemplifies the user-friendly nature of manipulating files and extracting information from the command line using bash scripts.

In contrast to certain other programming languages, bash scripts offer a significantly more streamlined and efficient process. Users can rapidly write, test, and execute scripts without the need for extensive code.

The inclusion of the “test” command enhances the script’s versatility, ensuring seamless functionality across various systems and platforms. This attribute makes it an exceptional tool for any bash user, contributing to the adaptability and widespread usability of bash scripts.

#!/bin/bash
file=file2.txt
echo "whats inside this directory ?"
ls -l
echo
if [ -f "$file" ]
then
echo "$file exists"
else
echo "$file does not exist - creating the $file"
touch file2.txt
fi
echo "Whats inside this directory ?"
ls -l

Output

bash script 26

Sample 18 – Disk status

This bash script illustrates the utilization of the “df -h” command to obtain detailed information about disk space on a system. Leveraging the command line and bash scripting, the script efficiently collects information about the current disk status.

Executing the script with the “sudo” command allows for the retrieval of information on disk space and usage, even for active processes and files owned by other users. The script generates a file named “disk_status.txt” to store the gathered information, ensuring easy accessibility and retrieval.

Highlighting the versatility and potency of bash scripting, this file empowers users to effortlessly gather system information without the need for manual command input or navigating through the file system. With a single command, the script provides a swift and convenient method to retrieve information regarding the disk status of a system.

#!/bin/bash df -h

Output

bash script 27

Sample 19 – System uptime and current date

This bash script utilizes the “uptime” and “date” commands to retrieve information about the system’s uptime and the current date. The script commences by creating a string variable named “today” and assigning the output of the “date” command to it.

Subsequently, the script outputs a message containing the string value of “today” alongside the text “SYSTEM UPTIME info -“.

This straightforward bash script showcases the command line’s potency and the adaptability of bash scripting. Through the utilization of the wait command and string variables, users can swiftly and effortlessly access information about the system’s uptime and current date without the need for manual command input or file system navigation.

By incorporating the capability to create a file named “system_uptime.txt,” users can save this information for future reference, ensuring its accessibility while safeguarding against unauthorized access.

#!/bin/bash today=`date` echo "SYSTEM UPTIME info - $today" echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" uptime

Output

bash script 28

Sample 20 – Count the number of files

The subsequent bash script showcases the capability to tally the number of files within a directory, a crucial task for Linux users to monitor directory contents and ensure proper access control.

Initiating with the ls -l command, the script lists files within the directory, presenting their permissions and the process ID of the file owner. It subsequently prompts the user with the question “how many files are here?” and utilizes the ls -l * | wc -l command to count the number of files, encompassing any text files present. This script offers an efficient means to track and manage file counts within a directory.

#!/bin/bash
ls -l
echo "how many files are here?"
ls -l * | wc -l

Output

bash script 29

That concludes our discussion!

If you find yourself repeatedly performing tasks on your Linux computer, the monotony and time consumption can become overwhelming. This is precisely where bash scripting proves invaluable. By compiling all those terminal commands into a single script file, you can execute them swiftly whenever needed.

Gone are the days of typing each command from scratch. It’s a real time-saver, isn’t it? Additionally, sharing script files within a team becomes a breeze. This not only saves time for you and your colleagues but also eliminates repetitive work.

Bash scripting aids in avoiding monotony, facilitates the sharing of instructions, streamlines logical and bulk operations, and simplifies the process of maintaining configuration histories for tasks, projects, or devices. We trust that our bash scripting tutorial has equipped you with a solid understanding of automating your tasks effectively.

Frequently Asked Questions

The “wait” command pauses the script’s execution, ensuring that it waits for a designated process to finish before proceeding further.

In Bash Scripting, you can create a multi-line comment by encapsulating the text between “#” symbols, with one symbol at the beginning and end of each line of the comment.

In Bash Scripting, command line arguments can be retrieved by utilizing special variables such as “$1”, “$2”, “$3”, etc., to access each argument in sequence. For instance, if two command line arguments are used, “$2” will correspond to the second argument.

In Bash Scripting, conditional tests can be executed using the “if” statement. The commands within the “if” block are only executed if the specified condition is satisfied.

Utilize the if [ -f "file.txt" ]; then command to verify the existence of a file named “file.txt.”

The read command with the -p option is used to read user input with a prompt.

You can use the if [ -d "dir" ]; then command to check if a directory named “dir” exists.

Employ ./script.sh to execute a script titled “script.sh” in the present directory.