bash script
Linux

Bash Script Step By Step, You will love it

Today we are going to talk about bash scripting or shell scripting and how to write your first bash script. Actually, they are called shell scripts in general, but we are going to call them bash scripts because we are going to use bash among the other Linux shells.

There are zsh, tcsh, ksh and other shells.

In the previous posts, we saw how to use the bash shell and how to use Linux commands.

The concept of a bash script is to enter multiple Commands and process the results.

To run multiple commands in a single step from the shell, type them on the same line, separated by a semicolon.

pwd ; whoami

Actually, this is a bash script!!

The pwd command runs first, displaying the current working directory then the whoami command runs to show the currently logged in users.

You can run multiple commands as much as you wish, but with a limit. You can determine your max args using this command.

 getconf ARG_MAX

Well, What about putting the commands into a file, and when we need to run these commands we run that file only. This is called a bash script.

Now, create an empty file using the touch command. At the beginning of any bash script, we should define which shell we will use because there are many shells on Linux, bash shell is one of them.

Bash Script Shebang

The first line you type when writing a bash script is the (#!) followed by the shell you will use.

#! <=== this sign is called shebang.

#!/bin/bash

In bash scripting, the pound sign (#) is used to comment a line which is not processed by the shell. This line defines what shell we will use, which is bash shell in our case.

The shell commands are entered one per line, and you can write a comment by adding the pound sign at the beginning of the file like this:

You can use the semicolon and put multiple commands on the same line if you want to, but it is preferable to write commands on separate lines, this will make it simpler to read later.

Set Script Permission

After writing your bash script, save the file.

Now, all you need to do is to set that file to be executable in order to be able to run it, otherwise, it will give you permissions denied. You can review how to set permissions using chmod command.

bash script permission

chmod +x ./myscript

Then try run it by just typing it in the shell:

./myscript

And Yes, it is executed.

bash script first run

Print Messages

As we know from other posts, printing text is done by echo command.

Edit our file and type this:

Look at the output:

bash script echo command

Perfect! Now we can run commands and display text using echo command.

If you don’t know echo command or how to edit a file I recommend you to view previous articles about basic Linux commands

Using Variables

Variables allow you to store information for use with other commands in the script.

You can define 2 types of variables in your bash script:

  • Environment variables
  • User variables

Environment Variables

Sometimes you need to interact with system variables in your shell commands to process information. You can do this by using environment variables.

Notice that we put the $HOME system variable in the double quotation marks in the first string, and the shell script still knows it.

bash script global variables

What if we want to print the dollar sign itself?

echo "I have $1 in my pocket"

The script sees a dollar sign within quotes; it assumes you’re referencing a variable. The script attempts to display the variable $1 which is not defined so how to overcome that?

By using the escape character which is the backslash \ before the dollar sign like this:

echo "I have \$1 in my pocket"

Now the bash script will print the dollar sign as it is.

bash script escape dollar sign

User variables

Also, you can set and use your custom variables in the script.

Variables defined in the shell script maintain their values till bash script execution finished.

You can call user variables using the dollar sign like this:

 

bash script user variables

Command substitution

You can extract information from the output of a command and assign it to a variable and use it in your script.

The command substitution can be done in two ways:

  • The backtick character `
  • The $() format

Make sure when you type backtick character, it is not the single quotation mark.

You must enclose the command with two backticks like this:

mydir=`pwd`

Or the other way

mydir=$(pwd)

So the script could be like this:

The output of the command will be stored in that variable called mydir.

bash script command substitution

Math calculation

You can perform basic math calculations using $(( 2 + 2 )) format:

Just that easy.

bash script math

if-then statement

In many situations, you will have to write some conditionals in your bash scripts to control the script logic. Like if the value is greater than 5 do this else do that. You can imagine any logic you want.

The most basic structure of if-then statement is like this:

if command

then

commands

fi

and here is an example:

If the command runs without problems, the echo statement should display the text.

Let’s dig deeper and use other commands we know.

Maybe searching for a specific user in the user’s file /etc/passwd and if a record exists, it prints a message saying that the user is present.

bash script if-else

We use the grep command to search for the user in /etc/passwd file. You can check our tutorial about the grep command.

If the user exists, the bash script will print the message.

What if the user doesn’t exist? The script will exit the execution without telling us that the user doesn’t exist. OK, let’s improve the script more.

if-then-else Statement

The if-then-else statement looks like this:

if command

then

commands

else

commands

fi

If the first command runs and returns zero; which means success, it will not hit the commands after the else statement, otherwise, if the if statement returns non-zero; which means the statement condition fails, in this case, the shell will hit the commands after else statement.

bash script if-else

We are doing good till now, keep moving.

Now, what if we need more else statements.

Well, that is easy, we can achieve that by nesting if statements like this:

if command1

then

commands

elif command2

then

commands

fi

If the first command return zero; means success, it will execute the commands after it, else if the second command return zero, it will execute the commands after it, else if none of these return zero, it will execute the last commands only.

You can imagine any scenario here, maybe if the user doesn’t exist, create a user using the useradd command or do anything else.

Numeric Comparisons

You can perform a numeric comparison between two numeric values using numeric comparison checks like this:

number1 -eq number2 Checks if number1 is equal to number2.

number1 -ge number2 Checks if number1 is greater than or equal to number2.

number1 -gt number2 Checks if number1 is greater than number2.

number1 -le number2 Checks if number1 is less than or equal to number2.

number1 -lt number2 Checks if number1 is less than number2.

number1 -ne number2 Checks if number1 is not equal to number2.

As an example, we will try one of them and the rest is the same.

Note that the comparison statement is in square brackets as shown.

bash script numeric compare

The val1 is greater than 10 so it will run the first statement and prints the first echo.

String Comparisons

Performing comparisons on strings are so easy. The comparison functions used to evaluate two string values are:

string1 = string2 Checks if string1 is the same as string string2.

string1 != string2 Checks if string1 is not the same as string2.

string1 < string2 Checks if string1 is less than string2.

string1 > string2 Checks if string1 is greater than string2.

-n string1 Checks if string1 has a length greater than zero.

-z string1 Checks if string1 has a length of zero.

We can apply string comparison on our example:

bash script string compare

One tricky note about the greater than and less than for string comparisons, they MUST be escaped with the backslash because if you use the greater-than symbol only, it shows wrong results.

The shell treats it as an output redirection. So you should do it like that:

bash script string greater than

It runs but it gives this warning:

./myscript: line 5: [: too many arguments

To fix it, wrap the $vals with a double quotation, forcing it to stay as one string like this:

bash script string fix

One important note about greater than and less than for string comparisons. Check the following example to understand the difference:

bash script character case

sort myfile

likegeeks

Likegeeks

bash script sort order

The test condition considers the capital letters less than lowercase letters in test comparisons. Unlike the sort command which does the opposite.

String test comparisons use standard ASCII ordering, which means using each character’s ASCII numeric value to determine the sort order.

Unlike the sort command which uses the ordering defined in the system locale language settings.

File Comparisons

There are many file comparisons that you can do in the bash script:

-d my_file Checks if the file exists and is a directory.

-e my_file Checks if the file exists.

-f my_file Checks if its a file.

-r my_file Checks if the file is readable.

my_file nt my_file2 Checks if my_file is newer than my_file2.

my_file ot my_file2 Checks if my_file is older than my_file2.

-O file Checks if the file exists and is owned by the current user.

-G my_file Checks if the file exists and the default group is the same as the current user.

As they imply, you will never forget them.

Let’s pick one of them and take it as an example:

bash script file checking

We are not going to type every one of them as an example. You just type the comparison between the square brackets as it is and complete you script normally.

There are some other advanced if-then features but let’s make it in another post.

That’s for now. I hope you enjoy it and keep practicing more and more.

Thank you.