Linux Bash Tutorial for Beginners: First Look Into Bash Scripting

Bash is one of the most popular and powerful scripting tools available in Linux and Unix. People utilize it to script various commands in one file and then let bash execute them.

For example, cron – a utility program to run repeating tasks such as creating backup files – let you execute commands automatically at a defined time.

Learning the bash scripting language helps you to utilize its full potential. This bash scripting tutorial will help you understand the basics of bash and how to write a simple bash script.

What Is Bash?

Bash, short for Bourne-Again Shell, is a Unix shell and a command language interpreter. It interprets a shell scripting language and executes the commands.

To fully understand bash shell scripting, you’ll need to understand two aspects – shell and scripting.

Shell is a macro processor that uses commands to interact with your computer. This means that they can retrieve and process data or store information on a computer.

There are two major types of shells available in Unix systems:

  • Bourne-type shell (.sh). The original UNIX shell was developed by AT&T. The four classifications of Bourne shell are Korn shell (ksh), Bourne shell (sh), POSIX shell (sh), and Bourne-Again shell (bash).
  • C shell (.csh). Developed from the C programming language, it includes many interactive features like recalling command history and editing mechanisms. In addition, there’s also the TENEX C shell (tcsh), a revised and enhanced version of the C shell.

Scripting involves a text editor to compile all the shell commands into a new file with a .sh extension.

If you want to schedule a shell command, execute the script file instead of executing the command manually.

For example, using a cron job makes it possible to execute the script automatically at any defined time. It saves you time and helps avoid mistakes during the command execution, as you don’t have to type and execute them one by one on the Linux command line.

Why Use Bash Functions?

Bash scripts are a great tool to ease your workflow as they consolidate a lot of lengthy commands into a single executable script file. Now, let’s see the advantages of bash scripts in more detail:

  • Execute multiple commands with a single script. Having all of the commands in one script file makes it easier when executing it. Instead of repeatedly typing the commands, simply execute a single script.
  • Tasks automation. Automate the script execution at any defined time using cron’s time-based scheduler.
  • Well-structured commands. Compiling the commands into the script file, you can structure the sequence of commands so every time you run these commands using a bash script, it runs in perfect order.
  • Transparency. Since a shell script is a text file, people can open it and check the code easily. However, if you run the commands using another program with another scripting language such as C++, you’ll need to access the source code.
  • Transferable. Transfer a bash script to another Unix-based operating system, and it’ll still work, providing that the shell commands are available in that particular operating system.

Bash is available on almost all types of Unix-based operating systems and doesn’t require any separate installation. To check the list of available shells in your Unix operating system, type the following command:

cat/etc/shells

The output should show a list like this:

/bin/bash
/bin/sh
/bin/tcsh
/bin/csh

Getting Started With Bash Scripting

First, you will need a Linux command line, also known as a Linux terminal. It’s a program that contains the shell and lets you execute bash scripts.

Next, you’ll need a UNIX text editor such as VIM or GNU Nano. Use the text editor to write the commands and compile them in a .sh script file.

If you want to run a bash script on your VPS server, you’ll need to have SSH access to your VPS server.

Linux has a general command manual for bash. It contains complete information about bash, including descriptions of all technical terms and standard shell variables.

Type and execute the following command to display the manual in the terminal:

man bash

The next step is creating a .sh file using a text editor. For this tutorial, we’ll use the VIM text editor to create a file using the following command:

vim sampleFunction.sh

This sends the .sh file to edit and executes it in bash commands. Each bash shell script needs to start with #! followed by the path of the bash interpreter. To display the path of the bash script, type the following command:

which bash

It should produce the following output:

/bin/bash

This is the standard practice for the bash interpreter path in most Unix operating systems. Therefore, to let the shell know that it should run the commands using a bash interpreter, start the script with the following command.

#!/bin/bash

After using the VIM Text Editor, hit ESC to enter the command mode, and then type :wq to save and exit.

Now, let’s discuss some of the bash commands in more detail.

1. Comments

Comments help anyone who reads the script file understand how each command line works. They are not parsed during the execution of the script.

There are two ways to add comments into a bash script. The first method is by using # for a single-line comment.

#!/bin/bash
#Command below prints a Hello World text
echo “Hello, world!”

The second method is by using : followed by a . This method works for multiple-line comments.

#!/bin/bash
read a
: ‘ 
Check the input number is 
less than 10 or greater than 10 or equal to 10
‘
if [[ $a -lt 10]]
then
echo “The number is less than 10”
elif [[$a -gt 10]]
then
echo “The number is greater than 10”
else
echo “The number is equal to 10”
fi

2. Variables

Variables are symbols that represent a character, strings of characters, or numbers. You only need to type the variable name in a command line to use the defined strings or numbers.

First, you have to assign the variable. To do so, type the variable name and the string value like this example:

testvar=“This is a test variable”

In this case, testvar will be the variable’s name, and This is a test variable is the string value. When assigning a variable, we recommend using a variable name that’s easy to remember and represents its value.

To read the variable value in a command line, use the $ symbol at the beginning of the variable name. Take a look at the example below:

#!/bin/bash
testvar=“This is a test variable”
echo $testvar

The output of that command should be:

This is a test variable

This is because the second command line uses echo to print out the value of testvar.

Let’s take a look at how you can enter a string value by using the read command and make the script compare two values from different variables:

#!/bin/bash
echo “Enter a number” 
read a #The value entered in this command line will be stored as variable a
b=50 #The value of variable b
if [[$a -eq $b]]
then
echo “Same number”
else
echo “Different number”
fi

The output of that script should be as follows:

Enter a number
20
Different number

Note that line 3 is the interactive input value that becomes variable a.

Since the script compares variable a with a value of 20 and variable b with a value of 50, the script prints out the Different number text as defined in the script.

However, if the interactive input value is 50, here’s the output:

Enter a number
50
Same number

This example also uses conditional statements, which we will discuss later.

3. echo

echo is one of the more well-known commands in the programming language. There are various options you can use with echo to print the output in the terminal.

The first and most common use of echo is to output a standard text:

echo “This is the text”

The output of that command is This is the text. By default, when you use the echo command like this, the terminal will input a new line underneath that. If you want to echo an output without a new line, you can do so by using -n.

echo -n “This is the text”

To print the output in a new line, use the option \n. To enable the backslash (\), you need to include -e.

echo -e “This \nis \nthe \ntext”

The output of that command should look like this:

This
is
the
text

The option \t adds a horizontal tab space:

echo -e “\tThis is the text”

This command’s output will indent the text to the right:

This is the text

You can also combine two options. For example, combine \n and \t to make the text printed in a new line and indented to the right:

echo -e “\n\tThis \n\tis \n\tthe \n\ttext”

The output of that command should look like this:

       This
       is
       the
       text

4. Functions

A function compiles a set of commands into a group. If you need to execute the command again, simply write the function instead of writing the whole set of commands.

There are several ways of writing functions.

The first way is by starting with the function name and following it with parentheses:

function_name () {
first command
second command
}

Or, if you want to write it in a single command line:

function_name () { first command; second command; }

The second method to write a function is using the reserved word function followed by the function name. This eliminates the parentheses:

function function_name {
first command
second command
}

This method also has a single-line version:

function function_name { first command; second command; }

For example, we can write two functions with multiple echo commands:

#!/bin/bash
hello_world () {
echo “Hello, World!”
echo “This is a test function”
}
print_message () {
echo “Let’s learn bash programming”
echo “Enjoy this tutorial”
}
fi

Note that writing the function as the example above only defines the function and doesn’t execute the contained commands. To execute it, write the function name in the command line.

Now, let’s put the two examples above in a complete bash script, including its execution:

#!/bin/bash
#Define a hello world function
hello_world () {
echo “Hello, World!”
echo “This is a test function”
}
#Define a print message function
print_message () {
echo “Let’s learn bash programming”
}
#Execute the hello world function
hello_world
#Execute the print message function
print_message
fi

The output of that script should be as follows:

Hello, World!
This is a test function
Let’s learn bash programming
Enjoy this tutorial

5. Loops

Loops are useful if you want to execute commands multiple times. There are three types of loops you can run in bash – for, while, and until.

The for loop runs the command for a list of items:

#!/bin/bash
for item in [list]
do
[commands]
done

This example uses a for loop to print all the days of the week:

#!/bin/bash
for days in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
do
echo “Day: $days”
done

On line 2, “days” automatically becomes a variable, with the values being the day names that follow. Then, on the command echo, we use the symbol $ to call the variable values.

The output of that script should be as follows:

Day: Monday
Day: Tuesday
Day: Wednesday
Day: Thursday
Day: Friday
Day: Saturday
Day: Sunday

Notice that even with a single command line in the loop script, it prints out seven echo outputs.

The next type of loop is while. The script will evaluate the condition. If the condition is true, it will keep executing the commands until the output no longer meets the defined condition.

#!/bin/bash
while [condition]
do
[commands]
done

Let’s take a look at a simple example that involves a variable and increment operator, denoted as ((++)):

#!/bin/bash
i=0
while [$i -le 5]
do 
echo $i
((i++))
done

The variable starts with 0 value, and the increment operator will increase the value by one. The condition set is less than or equal to five, so the command will keep iterating until the output reaches five. The output of that script will be as follows:

0
1
2
3
4
5

The last type of loop, until, works the opposite way of while. It will iterate the command until the condition is false.

Suppose we want the same output as the while example above using the until loop. We can write the script like this:

#!/bin/bash
i=0
until [$i -gt 5]
do 
echo $i
((i++))
done

Now, this command will iterate until the output value reaches five. The output should be the same as the while loop:

0
1
2
3
4
5

6. Conditional Statements

Many programming languages use conditional statements like if, then, and else for decision-making. They execute the command and provide an output depending on the conditions. Conditional statements also work in bash script.

The if statement is followed by the conditional expression. After that, follow with then and the command to define the output of the condition. The script will execute the command if the condition expressed in the if statement is true.

Suppose you want to execute a different command if the condition is false. Instead of using then, add an else statement to the script and follow that up with the command.

Let’s take a look at simple if, then, and else statements. Before the statement, we will include a variable so the user can input a value:

#!/bin/bash
echo “Enter a number”
read num
if [[$num -gt 10]]
then
echo “The number is greater than 10”
else
echo “The number is not greater than 10”

7. Reading and Writing Files

There are several methods to read a file, with the cat command being the most popular one. Note that this command reads the whole file content.

To read the content line by line, use the read command and a loop. Before writing a script to read a file, be sure that the file exists in the first place.

For example, suppose we have a to-do.txt file that contains a to-do list:

Reply email
Finish report
Call clients
Team evaluation

Now, we use the cat and read commands in our bash script to read and print the content of the to-do.txt file. The first part of the script will use the cat command, while the second part will use the read command in a loop.

#!/bin/bash
echo “Reading the file using cat command”
content=’cat to-do.txt’
echo $content
echo “Reading the file using read command and loop”
filename=’to-do.txt’
while read line
do
echo $line
done<$filename

The output of the script should be as follows:

Reading the file using cat command
Reply email Finish report Call clients Team evaluation
Reading the file using read command and loop
Reply email
Finish report
Call clients
Team evaluation

To write a command output into a file, use the redirection operators, represented with the > and >> symbols, and follow it with a file name: 

output > filename
output >> filename

Be careful when choosing the operator. If the given file exists, the > operator overwrites its content to zero-length and writes the output. It means you’ll lose the existing file content. If the given file doesn’t exist, it will create a new file.

The >> operator, on the other hand, will add the output to any given file. If the file already exists, it will simply add the output to the content.

Here’s a simple redirection to write the output into a text file:

echo “Hello, world!” >> hello_world.txt

Redirection also works with the read command to write any interactive input. This script example will add the input value into the name.txt file:

#!/bin/bash
echo “Enter your name”
read Name
echo $Name >> name.txt

Because the script redirects the variable output into the file, you won’t see any output printed. To see the output by printing the file content, add the following command line to read the file:

echo ‘cat name.txt’

Make sure that you have the read and write permissions in the file to prevent the permission denied error. Also, if you want to write into existing files, make sure you type the correct file names.

Basic Bash Functions

After understanding some of the bash commands, we’ll take a look at more basic bash functions and other bash script examples.

Let’s start with a basic bash function:

#!/bin/bash
testfunction(){
   echo “My first function”
}
testfunction

If you save this script in testFunction.sh and execute it as ./testFunction.sh, then you will be able to see the output as:

My first function

echo prints the output on the console. If you swap the position of the function definition with the function call, it will result in an error:

#!/bin/bash
testfunction
testfunction(){
   echo “My first function”
}

The snippet above won’t work. It calls the function at the second command line and defines the function later at the third command line. In this case, when the interpreter tries to execute it, it can’t find the function.

Bash functions accept any number of parameters. The example below accepts two parameters:

#!/bin/bash
testfunction(){
   echo $1
   echo $2
}
testfunction “Hello” “World”

$1 and $2 represent the command line arguments, the dynamic inputs within the command. You can also use the command line arguments and perform bash functions. One such example is shown below:

#!/bin/bash
addition(){
   sum=$(($1+$2))
   return $sum
}
read -p “Enter a number: ” int1
read -p “Enter a number: ” int2
add $int1 $int2
echo “The result is : ” $?

The addition is assigned in a variable sum, and this is returned from the function. Bash functions always return one single value. Interactive input is taken by using read for both numbers. Finally, the result is printed using $?, which stores the return value $sum from the function.

Now, let’s look at another function example where we first create a directory and then change the path to point to the new location:

sampleFunction () {
mkdir -p $1
cd $1
}

To verify this function, execute the following command:

sampleFunction myDir

myDir creates a valid directory name. If you check the present working path using the pwd command, you’ll see that you are currently within the newly created myDir.

Other than functions, loops and conditional statements are popular in bash scripting. We’ll look into a few instances of using both in the same script:

#!/bin/bash
isvalid=true
count=1
while [ $isvalid ]
do
echo $count
if [ $count -eq 5 ];
then
break
fi
((count++))
done

The example above uses the while and if statements. This executes the while loop five times after checking the conditional statement.

The output of this should be:

1
2
3
4
5

The for loop can increment and decrement the counters. An example of a for loop is shown below:

#!/bin/bash
for (( count=10; count>0; count-- ))
do
echo -n “$count “
done

The output of this for loop should be:

10 9 8 7 6 5 4 3 2 1

With if statements, we can also define else if by using elif statement:

#!/bin/bash
echo “Enter a valid number”
read n
if [ $n -eq 101 ];
then
echo “This is first number”
elif [ $n -eq 510 ];
then
echo “This is second number”
elif [ $n -eq 999 ];
then
echo “This is third number”
else
echo “No numbers over here”
fi

We can also write that script using the case statement. In the case statements, ;; represents case break, so if the variable value meets any of the conditions, it jumps to the end of the script:

#!/bin/bash
echo “Enter a valid number”
read n
case $n in
101)
echo “This is the first number” ;;
510)
echo “This is the second number” ;;
999)
echo “This is the third number” ;;
*)
echo “No numbers over here” ;;
esac

Conclusion

Bash is a useful and easy-to-learn scripting tool for Unix and Linux operating systems. It helps consolidate many lengthy commands into a single executable script.

In this bash tutorial, we’ve covered just the basic commands:

  • Comments
  • Variables
  • Echo
  • Functions
  • Loops
  • Conditional statements
  • Reading and writing files

There is much more you can learn to utilize the full potential of bash.

Practice with the examples provided and continue exploring bash to write better and more efficient scripts. Good luck!

Author
The author

Edward S.

Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward's goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.