If you want to control your operating system and perform various operations on your OS, then bash is the right way to do it. Bash is a shell that allows you to interact with the system by providing them instructions to follow. A script contains instructions that help the system to carry out various tasks differently. Using scripts, you can automate the tasks to reduce human intervention. You can even provide multiple commands within the script, and all the commands will be executed whenever you run the script.
If you are new to bash and bash scripts, you can go through this article to get essential information about bash scripts. Let’s get started.
What is Shell?
A shell is a program known as a command interpreter that provides an interface for users to interact with their systems. One can control it using commands to perform various operations. You can use “command-line” or “terminal” interchangeably for the term shell. This program takes input from the keyboard rather than the GUI of the computer. On Linux systems, the bash acts as the shell program.
What is Bash?
Bash is an interpreter that interprets the commands given to the shell. The command can be a simple text that instructs the operating system to perform a specific task. Several commands can ease your work by automating those commands via bash scripts.
What is a Bash Script?
A script will tell the computer what to do and in what order, providing you with complete control over your system. The Bash script will instruct the bash shell on what actions to take and what task to perform.
A Bash script is a text file containing a series of commands that can be triggered via a command line (such as ls or cp). You can use any command line in your script, and it will perform the same way as the command will do on the command line. Similarly, any command you put into a script will run in the same way on the command line and do the same thing.
You only have to type the commands as you usually do, and they will behave the same.
Bash scripts have an extension of .sh (for example, myscript.sh).
Practical examples of Bash Scripting
Below are some practical examples where you can use Bash Scripting:
- You can monitor your Linux system.
- You can take data backup and create snapshots.
- You can dump Oracle or MySQL databases for backup.
- You can create an email-based alert system.
- You can check what processes are consuming your system resources.
- You can check memory-related information such as free and used memory.
- You can check all necessary network services and their status.
- You can check information about local or remote servers.
- You can configure servers such as BIND (DNS server) to add zone entries.
Advantages of using Bash Scripts
- Bash scripts are easy to use and create.
- It provides interactive debugging.
- It saves your time by automating complex tasks.
- You can automate the Sys Admin task.
- Without additional effort, you can execute Bash scripts on nearly any modern UNIX / Linux / BSD / Mac OS X operating system.
Disadvantages of using Bash Scripts
- You can face compatibility issues between different platforms.
- It shows slow execution speed when compared to other programming languages.
- Every time the new process will launch for almost every shell command.
Features of Bash Script
Bash script offers the following features:
- You can customize editing key sequences with key bindings.
- You can quickly generate menus using control structures, primarily the select construct.
- You can customize your system’s environment with its new options and variables.
- With its one-dimensional arrays, you can refer to and manipulate lists of data.
- You can load the built-ins dynamically and create your built-ins and load them into the running shell.
Hello World Bash Shell Script
As an example, we are creating a bash script using the most basic syntax. This script will print the “Hello World”. For this, we use the “echo” command from the terminal. We will create a new and straightforward file, “hello-world.sh” that will contain the following code.
#!/bin/bash echo “Hello World”
Now, after creating the file, we will give the execute permission to the file with the help of the “chmod” command, as shown below.
$ chmod +x hello-world.sh
How to run a Bash Script?
After creating the “hello-world.sh” shell script, it is time to execute this file to display the output. Before running the shell script, make sure that you are in the path as the script. However, it is not necessary to be on the same path as the script for script execution.
Execute the bash script using the below command.
$./hello-world.sh
The above command will display the following output:
Hello World
Example: Creating a simple backup Bash Shell Script
It is a practical bash script application that allows you to take a backup of your home directory. We use the “tar” command to create a compressed tarball of the complete home directory to take a backup. We will create a shell script with the name “backup.sh” and use the following code.
#!/bin/bash
tar -czf /tmp/my_home.tar.gz /home/linux_world
Then, you can run the “backup.sh” script to create the backup under the linux_world directory. To confirm the backup file’s creation, you can run the “ls” command on the “linux_world” directory.
Why use ./?
You have noticed that we have used the “./” before the “hello-world.sh” script while running the script above. Whenever we use the name on the command-line, Bash will search it in the series of directories available under the variable $PATH. You can use the “echo” command to get the paths available in the “PATH” variable below.
echo $PATH
/home/linux_world/bin:/usr/local/bin:/usr/bin:/bin
The directories are separated by “:”. Bash will look in these specified directories only and ignore the sub-directories and the current working directory. Bash will go through the mentioned directories in the specific order and execute the first instance of the script that it will find.
Important Bash Components
Variables
With variables, you can store, alter, and reuse the data throughout your script. You can create a bash script “variable.sh” with the following code.
#!/bin/bash
greeting=”Hey”
user=$(whoami)
day=$(date +%A)
echo “$greeting $Hello $user! Today is $day
Now, give the executable permission to the file and execute it. After running the “variable.sh” file, you will get the following output.
Hey Hello Sam! Today is Wednesday
In the above example, we have used three variables. First, it takes the string value, the second contains the username running the shell session, and the third will display the current day. Then we used the echo command to display the output after substituting the variable names with their respective values. You can use the variables in the command terminal directly.
Input, Output, and Error Redirection
Whenever you run the terminal commands, it may either provide output, take input, or throw an error depending on the type of the running command.
Considering the following example, we find the file “data” that returns an error (stderr). Then we create the file “data” using the “touch” command and then run the “ls” command to check the “data” file again and will get the standard output (stdout).
The main difference between stdout and stderr output is that it will redirect each output separately. The > will redirect stdout to a file, while on the other hand, 2> will redirect stderr and &> will redirect to stdout and stderr. You can execute the cat command to display the content of the given file.
Consider the following example.
Functions
Functions are mainly used to organize and reuse code, thus increasing the script’s efficiency, execution speed, and readability.
If you do not use functions for complex problems, you will have inefficient and hard-to troubleshoot code. Here, we are using an example to create a simple function that will print the user information and make two function calls for both the information.
We will create a script named “function.sh” that will use the function user_details and its body enclosed inside curly brackets. Whenever you call the function, both echo commands will execute.
vi function.sh
Now, you can make this script executable by giving appropriate permissions and then running it.
$./function.sh
Numeric and String comparison
Using comparisons, you can easily compare strings and integers. Consider the following comparison operators table for both numeric and strings.
Description | Numeric Comparison | String Comparison |
less than | -lt | < |
greater than | -gt | > |
equal | -eq | #ERROR! |
not equal | -ne | != |
less or equal | -le | N/A |
greater or equal | -ge | N/A |
Below is the compare.sh script that will compare a string and an integer variable.
vi compare_values.sh
Output-
$ chmod +x compare_values.sh
$ ./compare_values.sh
Are UNIX and GNU strings equal?
1
Is 100 equal to 100 ?
0
Conditional Statements
You can make decisions by using conditional statements within a script based on specific conditions. The three conditional statements are if, then, and else. Below are the constructs for if, then, and else statements.
Example 1:
The above example will check the two variables num_a and num_b. If the condition is true, the echo statement will be printed, or there will be no output.
Example 2:
In the above example, if the if statement is true, then the first echo statement will be displayed as output, else the second else statement will get displayed as output.
Bash Loops
Loops are used to iterate through several tasks until a predefined condition is met. It will help in carrying out even time-consuming tasks quickly. There are three basic types of loops available like any other programming language.
For loop-
for loop is usually used to iterate through specific code several times.
While Loop-
This loop structure will work on a given condition, which means the code enclosed within the “do” and “done” will keep on executing until the specified condition will hold false.
Until Loop-
This loop is the opposite of the while loop and acts on the preset conditions. The code will get executed again and again until the condition changes from false to true.
Conclusion
Bash is the interpreter that helps users interact with the operating system by executing commands via a command-line interface. Within a bash script, you can include multiple commands and automate complex tasks. If you are a Linux user, you must know how to create and execute the bash scripts as it is the easiest way to control your system. This article highlights the basics of bash, bash script, and its various components.