Bash Scripting Tutorial
Bash Scripting Tutorial
In Linux, process automation relies heavily on shell scripting. This involves creating a file
containing a series of commands that can be executed together.
In this article, we'll start with the basics of bash scripting which includes variables, commands,
inputs/ outputs, and debugging. We'll also see examples of each along the way.
By saving these commands in a script, you can repeat the same sequence of steps multiple times
and execute them by running the script.
BASH SCRIPTING TUTORIAL LINUX
• Automation: Shell scripts allow you to automate repetitive tasks and processes, saving
time and reducing the risk of errors that can occur with manual execution.
• Portability: Shell scripts can be run on various platforms and operating systems,
including Unix, Linux, macOS, and even Windows through the use of emulators or virtual
machines.
• Flexibility: Shell scripts are highly customizable and can be easily modified to suit
specific requirements. They can also be combined with other programming languages or
utilities to create more powerful scripts.
• Accessibility: Shell scripts are easy to write and don't require any special tools or
software. They can be edited using any text editor, and most operating systems have a
built-in shell interpreter.
• Integration: Shell scripts can be integrated with other tools and applications, such as
databases, web servers, and cloud services, allowing for more complex automation and
system management tasks.
• Debugging: Shell scripts are easy to debug, and most shells have built-in debugging and
error-reporting tools that can help identify and fix issues quickly.
Overview of Bash shell and command line interface
The terms "shell" and "bash" are used interchangeably. But there is a subtle difference between
the two.
The term "shell" refers to a program that provides a command-line interface for interacting with
an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux
shells and is the default shell in many Linux distributions.
The shell accepts commands from the user and displays the output
In the above output, zaira@Zaira is the shell prompt. When a shell is used interactively, it
displays a $ when it is waiting for a command from the user.
If the shell is running as root (a user with administrative rights), the prompt is changed to #. The
superuser shell prompt looks like this:
[root@host ~]#
Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh),
C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all
share the common purpose of providing a command-line interface for interacting with the
operating system.
[username@host ~]$
You can enter any command after the $ sign and see the output on the terminal.
Generally, commands follow this syntax:
#!/bin/bash
BASH SCRIPTING TUTORIAL LINUX
You can find your bash shell path (which may vary from the above) using the command:
which bash
Creating our first bash script
Our first script prompts the user to enter a path. In return, its contents will be listed.
Create a file named run_all.sh using the vi command. You can use any editor of your choice.
vi run_all.sh
Add the following commands in your file and save it:
#!/bin/bash
echo "Today is " `date`
echo -e "\n you path has the following files and folders: "
ls $the_path
Script to print contents of a user supplied directory
Let's take a deeper look at the script line by line. I am displaying the same script again, but this
time with line numbers.
1 #!/bin/bash
2 echo "Today is " `date`
3
4 echo -e "\nenter the path to directory"
5 read the_path
6
7 echo -e "\n you path has the following files and folders: "
8 ls $the_path
• Line #1: The shebang (#!/bin/bash) points toward the bash shell path.
• Line #2: The echo command is displaying the current date and time on the terminal. Note
that the date is in backticks.
• Line #5: The read command reads the input and stores it in the variable the_path.
• line #8: The ls command takes the variable with the stored path and displays the current
files and folders.
BASH SCRIPTING TUTORIAL LINUX
Executing the bash script
To make the script executable, assign execution rights to your user using this command:
• chmod modifies the ownership of a file for the current user :u.
• +x adds the execution rights to the current user. This means that the user who is the
owner can now run the script.
• run_all.sh is the file we wish to run.
You can run the script using any of the mentioned methods:
• sh run_all.sh
• bash run_all.sh
• ./run_all.sh
Let's see it running in action
There are no data types in Bash. In Bash, a variable is capable of storing numeric values,
individual characters, or strings of characters.
In Bash, you can use and set the variable values in the following ways:
country=Pakistan
2. Assign the value based on the output obtained from a program or command, using command
substitution. Note that $ is required to access an existing variable's value.
same_country=$country
This assigns the value of countryto the new variable same_country
To access the variable value, append $ to the variable name.
zaira@Zaira:~$ country=Pakistan
zaira@Zaira:~$ echo $country
Pakistan
zaira@Zaira:~$ new_country=$country
zaira@Zaira:~$ echo $new_country
Pakistan
Assigning and printing variable values
Variable naming conventions
In Bash scripting, the following are the variable naming conventions:
6. Avoid using reserved keywords, such as if, then, else, fi, and so on as variable names.
Here are some examples of valid variable names in Bash:
name
count
_var
myVar
MY_VAR
And here are some examples of invalid variable names:
BASH SCRIPTING TUTORIAL LINUX
echo -e "\nyour path has the following files and folders: "
ls $the_path
This code reads each line from a file named input.txt and prints it to the terminal. We'll study
while loops later in this article.
while read line
do
echo $line
done < input.txt
BASH SCRIPTING TUTORIAL LINUX
3. Command line arguments
In a bash script or function, $1 denotes the initial argument passed, $2 denotes the second
argument passed, and so forth.
This script takes a name as a command-line argument and prints a personalized greeting.
Displaying output
Here we'll discuss some methods to receive output from the scripts.
2. Writing to a file:
ls > files.txt
This lists the files in the current directory and writes the output to a file named files.txt. You can
redirect output of any command to a file this way.
BASH SCRIPTING TUTORIAL LINUX
Basic Bash commands (echo, read, etc.)
Here is a list of some of the most commonly used bash commands:
(( i += 1 ))
done
While loop that iterates 10 times.
For loop
The for loop, just like the while loop, allows you to execute statements a specific number of
times. Each loop differs in its syntax and usage.
In the example below, the loop will iterate 5 times.
#!/bin/bash
for i in {1..5}
do
echo $i
done
For loop that iterates 5 times.
Case statements
In Bash, case statements are used to compare a given value against a list of patterns and
execute a block of code based on the first pattern that matches. The syntax for a case statement
in Bash is as follows:
case expression in
pattern1)
# code to execute if expression matches pattern1
;;
BASH SCRIPTING TUTORIAL LINUX
pattern2)
# code to execute if expression matches pattern2
;;
pattern3)
# code to execute if expression matches pattern3
;;
*)
# code to execute if none of the above patterns match expression
;;
esac
Case statements syntax
Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3",
and so on are the patterns that we want to compare it against.
The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk
"*" represents the default case, which executes if none of the specified patterns match the
expression.
fruit="apple"
case $fruit in
"apple")
echo "This is a red fruit."
;;
"banana")
echo "This is a yellow fruit."
;;
"orange")
echo "This is an orange fruit."
;;
*)
echo "Unknown fruit."
;;
esac
Example of case statement
In this example, since the value of "fruit" is "apple", the first pattern matches, and the block of
code that echoes "This is a red fruit." is executed. If the value of "fruit" were instead "banana",
the second pattern would match and the block of code that echoes "This is a yellow fruit." would
execute, and so on. If the value of "fruit" does not match any of the specified patterns, the
default case is executed, which echoes "Unknown fruit."
BASH SCRIPTING TUTORIAL LINUX
How to Schedule Scripts using cron
Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By
configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or specific
time basis. The automation capabilities provided by cron play a crucial role in Linux system
administration.
*/5 * * * *
*/5 * * * * Run a script every 5 minutes /path/to/script.sh
0 6 * * 1-5
0 6 * * 1-5 Run a script at 6 am from Monday to Friday /path/to/script.sh
0 0 1-7 * *
0 0 1-7 * * Run a script on the first 7 days of every month /path/to/script.sh
Using crontab
The crontab utility is used to add and edit the cron jobs.
crontab -l lists the already scheduled scripts for a particular user.
You can add and edit the cron through crontab -e.
You can read more about corn jobs in my other article here.
How to Debug and Troubleshoot Bash Scripts
Debugging and troubleshooting are essential skills for any Bash scripter. While Bash scripts can
be incredibly powerful, they can also be prone to errors and unexpected behavior. In this section,
we will discuss some tips and techniques for debugging and troubleshooting Bash scripts.
set -x
if [ $? -ne 0 ]; then
echo "Error occurred."
fi
Use echo statements
Another useful technique for debugging Bash scripts is to insert echo statements throughout your
code. This can help you identify where errors are occurring and what values are being passed to
variables.
#!/bin/bash
set -e