LinuxUncategorized

Bash Scripting: Baby Steps

Bourne Again Shell

Bash Shell Scripting Definition

Bash

Bash Scripting Intro

Bash is a command language interpreter. It is widely available on various operating systems and is a default command interpreter on most GNU/Linux systems. The name is an acronym for the ‘Bourne-Again SHell’.
Shell
Shell is a macro processor which allows for an interactive or non-interactive command execution.
Scripting
Scripting allows for an automatic commands execution that would otherwise be executed interactively one-by-one.

Bash Shell Script Basics

Do not despair if you have not understood any of the above Bash Shell Scripting definitions. It is perfectly normal, in fact, this is precisely why you are reading this Bash Scripting tutorial.

In case you did not know, Bash Scripting is a must skill for any Linux system administration job even though it may not be implicitly requested by the employer.

What is Shell

Most likely, your are at the moment sitting in front of your computer, have a terminal window opened and wondering: “What should I do with this thing?”

Well, the terminal window in front of you contains shell, and shell allows you by use of commands to interact with your computer, hence retrieve or store data, process information and various other simple or even extremely complex tasks.

Try it now! Use your keyboard and type some commands such as date, cal, pwd or ls followed by the ENTER key.

What you have just done, was that by use of commands and shell you interacted with your computer to retrieve a current date and time (date), looked up a calendar (cal), checked the location of your current working directory (pwd) and retrieved a list of all files and directories located within (ls).

What is Scripting

Now, imagine that the execution of all the above commands is your daily task. Every day you are required to execute all of the above commands without fail as well as store the observed information. Soon enough this will become an extremely tedious task destined for failure. Thus the obvious notion is to think of some way to execute all given commands together. This is where scripting becomes your salvation.

To see what is meant by scripting, use shell in combination with your favorite text editor eg. vi to create a new file called task.sh containing all the above commands, each on a separate line. Once ready, make your new file executable using chmod command with an option +x. Lastly, execute your new script by prefixing its name with ./.

As you can see, by use of scripting, any shell interaction can be automated and scripted. Furthermore, it is now possible to automatically execute our new shell script task.sh daily at any given time by use of cron time-based job scheduler and store the script’s output to a file every time it is executed. However, this is a tale for an another day, for now let’s just concentrate on a task ahead.

What is Bash

So far we have covered shell and scripting. What about Bash? Where does the bash fit in? As already mentioned, the bash is a default interpreter on many GNU/Linux systems, thus we have been using it even without realising. This is why our previous shell script works even without us defining bash as an interpreter. To see what is your default interpreter execute command echo $SHELL:

$ echo $SHELL
/bin/bash

There are various other shell interpreters available, such as Korn shell, C shell and more. From this reason, it is a good practice to define the shell interpreter to be used explicitly to interpret the script’s content.

To define your script’s interpreter as Bash, first locate a full path to its executable binary using which command, prefix it with a shebang #! and insert it as the first line of your script. There are various other techniques how to define shell interpreter, but this is a solid start.

Hello World Bash Shell Script

Now, it is time to write our first, most basic bash shell script. The whole purpose of this script is nothing else but print “Hello World” using echo command to the terminal output. Using any text editor create a new file named hello-world.sh containing the below code:

#!/bin/bash

echo "Hello World"

Once ready, make your script executable with thechmod command and execute it using relative path ./hello-world.sh:

$ chmod +x hello-world.sh 
$ linuxconfig.org:~$ ./hello-world.sh 
Hello World
$ 

The following video example offers an alternative way of creating the above hello-world.sh script. It uses which command to print a full path to the bash interpreter. This output is simultaneously redirected using > redirection sign while creating a new file hello-world.sh at the same time.

Simple Backup Bash Shell Script

Let’s discuss a command line execution and how GNU/Linux commands fit into the shell script creation process in more detail.

Any command which can be successfully executed directly via bash shell terminal can be in the same form used as part of bash shell script. In fact, there is no difference between command execution directly via terminal or within a shell script apart from the fact that the shell script offers non-interactive execution of multiple commands as a single process.

 Quick Tip:Regardless of the script complexity, do not attempt to write your entire script in one go. Slowly develop your script by testing each core line by executing it first on the terminal command line. When successful, transfer it to your shell script.

Additionally, most commands accept so called options and arguments. Command options are used to modify command’s behaviour to produce alternative output results and are prefixed by -. Arguments may specify command’s execution target such as file, directory, text and more.

Each command comes with a manual page which can be used to learn about its function as well as what options and arguments each specific command accepts.

Use man command to display manual page of any desired command. For example to display a manual page for the ls command execute man ls. To quit from manual page press q key.

The below ls command example shows a basic use of command line options and arguments.

Although our first “Hello World” shell script requires a solid understanding of the file creation, editing and script execution, its usability can be clearly questioned.

The next example offers more practical application as it can be used to backup our user home directory. To create the backup script, on Line 3we will be using tar command with various options -czf in order to create a compressed tar ball of entire user home directory /home/linuxconfig/. Insert the following code into a new file called backup.sh, make the script executable and run it:

#!/bin/bash

tar -czf /tmp/myhome_directory.tar.gz /home/linuxconfig

 

 Quick Tip:Enter man tar command to learn more about all tar command line options used within the previous backup.sh script. Try to run the tar command without - option prefix! Does it work?

Variables

Variables are the essence of programming. Variables allow a programmer to store data, alter and reuse them throughout the script. Create a new script welcome.sh with the following content:

#!/bin/bash

greeting="Welcome"
user=$(whoami)
day=$(date +%A)

echo "$greeting back $user! Today is $day, which is the best day of the entire week!"
echo "Your Bash shell version is: $BASH_VERSION. Enjoy!"

By now you should possess all required skills needed to create a new script, making it executable and running it on the command line. After running the above welcome.sh script, you will see an output similar to the one below:

$ ./welcome.sh 
Welcome back linuxconfig! Today is Wednesday, which is the best day of the entire week!
Your Bash shell version is: 4.4.12(1)-release. Enjoy!

Let’s look at the script more closely. First, we have declared a variable greeting and assigned a string value Welcome to it. The next variable user contains a value of user name running a shell session. This is done through a technique called command substitution. Meaning that the output of the whoami command will be directly assigned to the user variable. The same goes for our next variable day which holds a name of today’s day produced by date +%A command.

The second part of the script utilises the echo command to print a message while substituting variable names now prefixed by $ sign with their relevant values. In case you wonder about the last variable used $BASH_VERSION know that this is a so called internal variable defined as part of your shell.

 Quick Tip:Never name your private variables using UPPERCASE characters. This is because uppercase variable names are reserved for internal shell variables, and you run a risk of overwriting them. This may lead to the dysfunctional or misbehaving script execution.

Variables can also be used directly on the terminal’s command line. The following example declares variables a and b with integer data. Using echo command, we can print their values or even perform an arithmetic operation as illustrated by the following example:

Now that we have bash variable introduction behind us we can update our backup script to produce more meaningful output file name by incorporating a date and time when the backup on our home directory was actually performed.

Furthermore, the script will no longer be bind to a specific user. From now on our backup.sh bash script can be run by any user while still backing up a correct user home directory:

#!/bin/bash

# This bash script is used to backup a user's home directory to /tmp/.

user=$(whoami)
input=/home/$user
output=/tmp/${user}_home_$(date +%Y-%m-%d_%H%M%S).tar.gz

tar -czf $output $input
echo "Backup of $input completed! Details about the output backup file:"
ls -l $output

You may have already noticed that the above script introduces two new bash scripting concepts. Firstly, our new backup.sh script contains comment line. Every line starting with # sign except shebang will not be interpreted by bash and will only serve as a programmer’s internal note.

Secondly, the script uses a new shell scripting trick ${parameter} called parameter expansion. In our case, curly braces {} are required because our variable $user is followed by characters which are not part of its variable name. Below is the output of our newly revised backup script:

$ ./backup.sh 
tar: Removing leading `/' from member names
Backup of /home/linuxconfig completed! Details about the output backup file:
-rw-r--r-- 1 linuxconfig linuxconfig 8778 Jul 27 12:30 /tmp/linuxconfig_home_2017-07-27_123043.tar.gz

Comment here