Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System. It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to automate different types of tasks in a system. Developers can avoid doing repetitive tasks using bash scripting.
Bash scripting supports variables, conditional statements, and loops just like programming languages. Below are some of the applications of Bash Scripts –
Applications of Bash Scripts:
- Manipulating files
- Executing routine tasks like Backup operation
- Automation
The advantages of using Bash Scripts are given below –
Advantages of Bash Scripts:
- It is simple.
- It helps to avoid doing repetitive tasks
- Easy to use
- Frequently performed tasks can be automated
- A sequence of commands can be run as a single command.
The disadvantages of the Bash Scripts are given below –
Disadvantages of Bash Scripts:
- Any mistake while writing can be costly.
- A new process launched for almost every shell command executed
- Slow execution speed
- Compatibility problems between different platforms
How to Write Bash Scripts?
To write a Bash Script we will follow the steps –
- First, we will create a file with the .sh extension.
- Next, we will write down the bash scripts within it
- After that, we will provide execution permission to it.
To create and write a file with the .sh extension we can use gedit text editor. The command for it will be –
gedit scriptname.sh
The first line of our script file will be –
#!/bin/bash
This will tell, the system to use Bash for execution. Then we can write our own scripts.
Let’s write down just a simple script that will print some lines in the terminal. The code for it will be –
#!/bin/bash
echo "Hello, GeeksforGeeks"
Now we will save the file and provide the execution permission to it. To do so use the following command –
chmod +x scriptname.sh
Next to execute the following script we will use the following command –
./scriptname.sh
Here is the terminal shell pictorial depiction after executing the above commands as follows:
Here the script file name is gfg.sh.
Now we can also write more complicated commands using Bash Scripts. Here is an example below in which we are using a condition statement –
Example Script:
#!/bin/bash
Age=17
if [ "$Age" -ge 18 ]; then
echo "You can vote"
else
echo "You cannot vote"
fi
Output:
You cannot vote
Here is the terminal shell pictorial depiction after executing the above script as follows:
In the above way, we can execute multiple Bash commands all at once.
Comments
Post a Comment