25-03-2021

If you have to do it more than once, automate it!

Download Shell Script Loader for free. A framework for modular scripting. Shell Script Loader is a framework for shell scripts that provides functions that can be used to load, include or call module shell scripts. It supports most shells including Bash, Zsh, Ksh, and other shells based on sh. Sample scripts for system administration. A collection of examples walks through scenarios for administering systems with PowerShell.

You will often find yourself repeating a single task on Linux over and over again. It may be a simple backup of a directory or it could be cleaning up temporary files or it can even be cloning of a database.

Automating a task is one of the many useful scenarios where you can leverage the power of bash scripting.

Let me show you how to create a simple bash shell script, how to run a bash script and what are the things you must know about shell scripting.

Create and run your first shell script

Free Shell Scripting Books

Let’s first create a new directory named scripts that will host all our bash scripts.

Now inside this 'scripts directory', create a new file named hello.sh using the cat command:

Insert the following line in it by typing it in the terminal:

Press Ctrl+D to save the text to the file and come out of the cat command.

You can also use a terminal-based text editor like Vim, Emacs or Nano. If you are using a desktop Linux, you may also use a graphical text editor like Gedit to add the text to this file.

So, basically you are using the echo command to print 'Hello World'. You can use this command in the terminal directly but in this test, you'll run this command through a shell script.

Now make the file hello.sh executable by using the chmod command as follows:

Scripts

And finally, run your first shell script by preceding the hello.sh with your desired shell “bash”:

You'll see Hello, World! printed on the screen. That was probably the easiest Hello World program you have ever written, right?

Here's a screenshot of all the steps you saw above:

Convert your shell script into bash script

Confused? Don't be confused just yet. I'll explain things to you.

Bash which is short for “Bourne-Again shell” is just one type of many available shells in Linux.

A shell is a command line interpreter that accepts and runs commands. If you have ever run any Linux command before, then you have used the shell. When you open a terminal in Linux, you are already running the default shell of your system.

Bash is often the default shell in most Linux distributions. This is why bash is often synonymous to shell.

The shell scripts often have almost the same syntaxes, but they also differ sometimes. For example, array index starts at 1 in Zsh instead of 0 in bash. A script written for Zsh shell won't work the same in bash if it has arrays.

To avoid unpleasant surprises, you should tell the interpreter that your shell script is written for bash shell. How do you do that? You use shebang!

The SheBang line at the beginning of shell script

The line “#!/bin/bash” is referred to as the shebang line and in some literature, it’s referred to as the hashbang line and that’s because it starts with the two characters hash ‘#’ and bang ‘!’.

When you include the line “#!/bin/bash” at the very top of your script, the system knows that you want to use bash as an interpreter for your script. Thus, you can run the hello.sh script directly now without preceding it with bash.

Adding your shell script to the PATH (so that it can be run from any directory)

Free Shell Script

You may have noticed that I used ./hello.sh to run the script; you will get an error if you omit the leading ./

Bash thought that you were trying to run a command named hello.sh. When you run any command on your terminal; they shell looks for that command in a set of directories that are stored in the PATH variable.

You can use echo to view the contents of that PATH variable:

The colon character (:) separates the path of each of the directories that your shell scans whenever you run a command.

Linux commands like echo, cat etc can be run from anywhere because their executable files are stored in the bin directories. The bin directories are included in the PATH. When you run a command, your system checks the PATH for all the possible places it should look for to find the executable for that command.

If you want to run your bash script from anywhere, as if it were a regular Linux command, add the location of your shell script to the PATH variable.

First, get the location of your script's directory (assuming you are in the same directory), use the PWD command:

Use the export command to add your scripts directory to the PATH variable.

Notice that I have appended the 'scripts directory' to the very end to our PATH variable. So that the custom path is searched after the standard directories.

The moment of truth is here; run hello.sh:

It works! This takes us to end of this tutorial. I hope you now have some basic idea about shell scripting.

Since I introduced you to PATH variable, stay tuned for the next bash scripting tutorial where I discuss shell variables in detail.

Become a Member for FREE
Become a member to get the regular Linux newsletter (2-4 times a month) and access member-only content

Join the conversation.

Free Shell Script

Arguments can be useful, especially with Bash!

So far, you have learned how to use variables to make your bash scripts dynamic and generic, so it is responsive to various data and different user input.

In this tutorial, you will learn how you can pass variables to a bash scripts from the command line.

Passing argument to a bash shell script

The following script count_lines.shwill output the total number of lines that exist in whatever file the user enters:

For example, the user can enter the file /etc/passwdand the script will spit out the number of lines as a result:

This script works fine; however, there is a much better alternative!

Instead of prompting the user for the filename, we can make the user simply pass the filename as a command line argument while running the script as follows:

The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1 variable.

So in the count_lines.sh script, you can replace the filename variable with $1 as follows:

Notice that I also got rid of the read and first echo command as they are no longer needed!

Finally, you can run the script and pass any file as an argument:

Passing multiple arguments to a bash shell script

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script:

The second argument will be referenced by the $2 variable, the third argument is referenced by $3, .. etc.

The $0 variable contains the name of your bash script in case you were wondering!

Now we can edit our count_lines.shbash script so that it can count the lines of more than one file:

You can now run the script and pass three files as arguments to the bash script:

As you can see, the script outputs the number of lines of each of the three files; and needless to say that the ordering of the arguments matters, of course.

Getting creative with arguments in Bash shell

Free Shell Script

There are a whole lot of Linux commands out there.

Some of them are a bit complicated as they may have long syntax or a long array of options that you can use.

Fortunately, you can use bash arguments to turn a hard command into a pretty easy task!

To demonstrate, take a look at the following find.shbash script:

It’s a very simple script that yet can prove very useful! You can supply any filename as an argument to the script and it will display the location of your file:

You see how this is now much easier than typing the whole find command! This is a proof that you can use arguments to turn any long complicated command in Linux to a simple bash script.

If you are wondering about the 2> /dev/null, it means that any error message (like file cannot be accessed) won't be displayed on the screen. I suggest reading about stderr redirection in Linux to get more knowledge on this topic.

Shell Script For Each

Bonus Tip: Special variables in Bash shell

Bash has a lot of built-in special variables that are quite handy and are available at your disposal.

The table below highlights the most common special built-in bash variables:

Special VariableDescription
$0The name of the bash script.
$1, $2...$nThe bash script arguments.
$$The process id of the current shell.
$#The total number of arguments passed to the script.
[email protected]The value of all the arguments passed to the script.
$?The exit status of the last executed command.
$!The process id of the last executed command.

To see these special variables in action; take a look at the following variables.shbash script:

You can now pass any arguments you want and run the script:

Alright, this brings us to the end of this week’s tutorial. I hope you now realize how powerful and useful bash arguments can be; stay tuned for next week as I am going to show you can create and utilize arrays in your bash scripts.

Become a Member for FREE
Become a member to get the regular Linux newsletter (2-4 times a month) and access member-only content

Join the conversation.