WHAT IS A BASH SCRIPT
What is a Bash script?
Bash is a Unix command line interface for interacting with the operating system, available for Linux and macOS. Bash scripts help group commands to create a program. All instructions that run from the terminal work in Bash scripts as well.
Bash scripting is a crucial tool for system administrators and developers. Scripting helps automate repetitive tasks and interact with the OS through custom instruction combinations. The skill is simple to learn and requires only basic terminal commands to get started.
Bash is a type of interpreter that processes shell commands. A command is given in the form of plain text that calls operating system services to perform a task.
cd are frequently used by programmers; these commands are written in the terminal. The terminal acts as an interface for the shell interpreter.
Bash is just a shell that allows you to communicate with the computer and allow you to give instructions to it. A script is basically just a set of instructions given to the computer to execute different meaningful tasks. A script helps you automate different tasks along with the luxury to accomplish results faster than the normal procedure. Normally, in the terminal, you write a basic or advance bash command and it executes on it right away. In bash scripts, you could give multiple instructions or commands at once and the computer would execute all of them only when you would execute the script. In a nutshell, single bash command can be executed in the terminal but to execute a combination of multiple commands at once, you need to create a bash script.
What are bash scripts used for?
It is used to automate repetitive tasks on Linux filesystem. It might include a set of commands, or a single command, or it might contain the hallmarks of imperative programming like loops, functions, conditional constructs, etc.
A Bash script is a text file containing a series of commands.
Any command that can be executed in the terminal can be put into a Bash script. Any series of commands to be executed in the terminal can be written in a text file, in that order, as a Bash script.
Bash scripts are given an extension of
Let’s just say we have a Bash script,
bash_intro.sh, consisting of the following commands:
In order to run the above Bash script, run the following command in the terminal:
The shell will start executing the commands in the script in sequence; it will navigate to the DRP folder and then list its contents down in the terminal. See the output below:
Why bash is useful and who it is useful for?
If you want more control over your OS and want to perform different OS related tasks then bash is your way to go. By bash, we don’t only refer to the scripting language but also to the tools that come with Linux operating system. Every single tool on Linux has its work and each performs a different task individually. Bash is really useful whenever you need to combine all those tools and chain them together in such a way that they all work in harmony to accomplish a task which is really difficult to do otherwise. For example, anything that has something to do with the Linux OS can also be done in other programming languages such as Python or Perl but it’s very hard to accomplish different OS-related tasks. A simple, black & white and easiest way to do anything concerning Linux OS is by using bash. For anyone who wants to perform tasks that include the Linux OS tools (such as ls, cd, cat, touch, grep, etc.), it is really useful for him/her to learn bash instead of any other programming language.
Bash comparIson to other programming languages?
If we talk about bash then we know that bash is not a general-purpose programming language but a command-line interpreter. Bash is really useful to perform tasks around different tools and processes with the ability to combine different processes together and make all of them work towards a single goal. Bash is really handy when it comes to dealing and manipulating the inputs and outputs which is a really difficult thing to do in other general-purpose programming languages such as python, C, etc. However, when it comes to data structures and complex tasks such as manipulating complex data, bash cannot handle such tasks and we have to look towards programming languages such as Python, Perl, C, etc. In programming languages, you can build software or a tool but you cannot build either of them in bash. However, you can use bash to run the tools or merge those tools together to run efficiently. It’s like building a rocket, if we consider this metaphor, programming languages will help you build the rocket while bash will help you drive the rocket and help you set its direction and help you land it to the moon or mars.
How To Write a Bash Script In Linux
The first step is often the hardest, but don’t let that stop you. If you’ve ever wanted to learn how to write a shell script but didn’t know where to start, this is your lucky day.
If this is your first time writing a script, don’t worry — shell scripting is not that complicated. That is, you can do some complicated things with shell scripts, but you can get there over time. If you know how to run commands at the command line, you can learn to write simple scripts in just 10 minutes. All you need is a text editor and an idea of what you want to do. Start small and use scripts to automate small tasks. Over time you can build on what you know and wind up doing more and more with scripts.
Each script starts with a “shebang” and the path to the shell that you want the script to use, like so:
The “#!” combo is called a shebang by most Unix geeks. This is used by the shell to decide which interpreter to run the rest of the script, and ignored by the shell that actually runs the script. Confused? Scripts can be written for all kinds of interpreters — bash, tsch, zsh, or other shells, or for Perl, Python, and so on. You could even omit that line if you wanted to run the script by sourcing it at the shell, but let’s save ourselves some trouble and add it to allow scripts to be run non-interactively.
What’s next? You might want to include a comment or two about what the script is for. Preface comments with the hash (#) character:
#!/bin/bash # A simple script
Let’s say you want to run an rsync command from the script, rather than typing it each time. Just add the rsync command to the script that you want to use:
#!/bin/bash # rsync script rsync -avh --exclude="*.bak" /home/user/Documents/ /media/diskid/user_backup/Documents/
Save your file, and then make sure that it’s set executable. You can do this using the chmod utility, which changes a file’s mode. To set it so that a script is executable by you and not the rest of the users on a system, use “chmod 700 scriptname” — this will let you read, write, and execute (run) the script — but only your user. To see the results, run ls -lh scriptname and you’ll see something like this:
-rwx------ 1 jzb jzb 21 2010-02-01 03:08 echo
The first column of rights, rwx, shows that the owner of the file (jzb) has read, write, and execute permissions. The other columns with a dash show that other users have no rights for that file at all.
The above script is useful, but it has hard-coded paths. That might not be a problem, but if you want to write longer scripts that reference paths often, you probably want to utilize variables. Here’s a quick sample:
#!/bin/bash # rsync using variables SOURCEDIR=/home/user/Documents/ DESTDIR=/media/diskid/user_backup/Documents/ rsync -avh --exclude="*.bak" $SOURCEDIR $DESTDIR
There’s not a lot of benefit if you only reference the directories once, but if they’re used multiple times, it’s much easier to change them in one location than changing them throughout a script.
Non-interactive scripts are useful, but what if you need to give the script new information each time it’s run? For instance, what if you want to write a script to modify a file? One thing you can do is take an argument from the command line. So, for instance, when you run “script foo” the script will take the name of the first argument (foo):
#!/bin/bash echo $1
Here bash will read the command line and echo (print) the first argument — that is, the first string after the command itself.
You can also use read to accept user input. Let’s say you want to prompt a user for input:
#!/bin/bash echo -e "Please enter your name: " read name echo "Nice to meet you $name"
That script will wait for the user to type in their name (or any other input, for that matter) and use it as the variable $name. Pretty simple, yeah? Let’s put all this together into a script that might be useful. Let’s say you want to have a script that will back up a directory you specify on the command line to a remote host:
That script will read in the input from the command line and substitute it as the destination directory at the target system, as well as the local directory that will be synced. It might look a bit complex as a final script, but each of the bits that you need to know to put it together are pretty simple. A little trial and error and you’ll be creating useful scripts of your own.
Of course, this is just scraping the surface of bash scripting.
Writing a Bash Script
To start with Bash scripting, create a new file using a text editor. If you’re using Vim, run the following command:
The extension for Bash scripts is .sh. However, the extension is not necessary. Adding the .sh makes the file easy to identify and maintain.
Adding the “shebang”
The first line in Bash scripts is a character sequence known as the “shebang.” The shebang is the program loader’s first instruction when executing the file, and the characters indicate which interpreter to run when reading the script.
Add the following line to the file to indicate the use of the Bash interpreter:
The shebang consists of the following elements:
#!directs the program loader to load an interpreter for the code in the file.
/bin/bashthe Bash interpreter’s location.
Some typical shebang lines for different interpreters are in the table below.
|Uses the |
After adding a shebang, continue to the next section.
Comments are lines that do not execute. However, they help with code readability. After the shebang, add a comment to explain what the script is.
#!/bin/bash # A simple Bash script
For more information on Bash comments and the best practices, read our article on how to comment in bash
As an example, create a script to update and upgrade the system. Add the lines after the Bash comment so the final script looks like the following:
#!/bin/bash # A simple Bash script sudo apt update -y sudo apt upgrade -y echo Done!
The Bash interpreter reads each line and executes the update command followed by the upgrade command. The -y tag automatically answers Yes to any prompt brought up by the two instructions. When completed, the program prints Done! to the console.
Save the code and exit the text editor
Executing the Bash Script
To run the bash script use the following command in the terminal:
The script prompts to enter the password to run the sudo commands. Enter the password and wait for the program to finish the update and upgrade.
Drop your comment