Bash Script Examples

In this tutorial, we will explain the most common bash operations while also showing you a few bash script examples.

A Unix shell program interprets instructions and programs in the form of commands. These commands are either directly entered by the user, or they can be run in sequence from a file (called a shell script). An important distinction of bash scripts when compared to other coding languages is that they are interpreted and not compiled. When you write a shell script and then run it, it’s interpreted by your operating system, with no compilation required.

Bash scripts are a versatile and handy tool that most system administrators love using to simplify their workflow and automate repetitive tasks. With scripts, you can do almost anything that you can do using a normal shell environment.

Requirements

  • A Linux VPS with root access enabled or a user with sudo privileges. All common distributions of Linux (Debian, Ubuntu, CentOS, Fedora, etc) are all able to run shell scripts.

1. The echo Command in Scripts

You can run a bash script from the terminal, or by executing it from a bash file that is saved on your computer or server.

Let’s write our first bash script example by creating a simple shell script file named test.sh that prints the line “Hello World”:

nano test.sh

The .sh extension is short for shell. Continue by adding the following lines:

#!/bin/bash
echo "Hello World"

To save, press Ctrl+O and then press enter to confirm the filename. Then press Ctrl+X to exit the nano text editor.

Once you have done the above, run the bash script using the following command:

bash test.sh

This will print the following output:

Hello World

This is a very simple command, however, it can be useful when debugging your script or when you want to display some information to the user.

2. Get User Input in a Bash Script

You can accept input from the keyboard and assign a value to a user-defined shell variable using the read command. This will read whatever is entered by the keyboard and save it to the variable.

To start, create a new bash script named input.sh:

nano input.sh

Add the following lines. These commands will display a question, take input from the user, and print the value entered while also combining it with a string.

#!/bin/bash
echo "What is Your Name?"
read name
echo "My Name is $name"

Save and close the file, then run the script using the following command:

bash input.sh

You will be asked to provide your name and print the message with other string as shown below:

What is Your Name?
John
My Name is John

3. If Statements in Bash Scripts

Bash if statements are very useful and allow us to make decisions in bash scripts. With if statements, you can decide whether or not to run a block of code based on a preset condition being met or not.

The basic syntax of if statement is shown below:

if [condition]; then

fi

Anything between the keywords then and fi will be executed only if the condition is true.

For better understanding, create a test-if.sh file:

nano test-if.sh

Here, the number 8 is assigned to the variable n. If the value of $n is less than 10, then the output will be “one-digit number”, otherwise the output will be a “two-digit number”. Note that there is no upper limit to the range, so even three-digit numbers will give “two digit number” as the output.

#!/bin/bash
n=9
if [ $n -lt 10 ];
then
echo "one digit number"
else
echo "two digit number"
fi

The -lt operator is a comparison tool. LT is short for “less than”. You can replace it and use -gt to check whether n is “greater than” the value on the right.

Save and close the file, then run the bash script example with the following command:

bash test-if.sh

You should see the following output:

one digit number

4. If Statements with AND logic in Bash

If you want to check for multiple conditions in a bash script, then you can use logic gates to accomplish this. The AND logic gate only returns TRUE when both comparisons being made are TRUE. AND logic can be defined using the symbol &&.

Create a new test-and.sh file where we can test this AND logic:

nano test-and.sh

Add the following lines:

echo "Enter your name"
read name
echo "Enter your age"
read age
if [[ ( $name == "john" && $age == "40" ) ]]; then
echo "you are right"
else
echo "you are wrong"
fi

Save and close the file, then run the newly-written script with the following command:

bash test-and.sh

This will ask for your name and age, and then compare it with AND logic. If both of the variables match the values that they are being compared to, then the output will be “you are right” – otherwise, the output will be “you are wrong”. Both values must be identical to the variables in order for the if statement to succeed.

Enter your name
john
Enter your age
40
you are right

5. If Statements with OR logic in Bash

The OR condition is also frequently used in bash scripts if you want to check for multiple conditions being met individually. An OR gate returns a TRUE value when one of any required conditions is met.

For example, create a test-or.sh script with the following contents:

nano test-or.sh

Add the following lines:

#!/bin/bash
echo "Enter any number between 1 and 99 which can be divided by 10"
read number
if [[ ( $number -eq 10 || $number  -eq 20 || $number -eq 30 || $number -eq 40 || $number -eq 50 || $number -eq 60 || $number -eq 70 || $number -eq 80 || $number -eq 90 ) ]]
then
echo "You are right"
else
echo "You are wrong"
fi

Save and close the file before running the script with the following command:

bash test-or.sh

This script will ask the user to enter any number between 1 and 99 that can be divided by 10. If the value is a number that can be divided by 10 (e.g. 10 or 20), then the output will be “You are right” – otherwise, the output will be “You are wrong”.

Enter any number between 1 and 99 which can be divided by 10
31
You are wrong
Enter any number between 1 and 99 which can be divided by 10
90
You are right

6. If-Else Statements in Bash

If-Else statements allow the shell interpreter to make the correct decision based on several conditions. If the condition in the if statement is not met, then a block of code between else and fi will be executed before continuing with the rest of the script. Note that if the if statement’s condition is met, then the code in the else block will not be executed. We’ll show you a bash script example on If-Else as well.

For example, create a test-else.sh file with the following contents:

nano test-else.sh

Add the following lines:

#!/bin/bash
a=10
b=20
if [ $a -gt $b ]
then
echo "a is greater than b"
else
echo "a is less than b"
fi

Save the file and exit the text editor. Run the script with the following command:

bash test-else.sh

This will print different messages based on whether the number is greater or less than the number it’s being compared to.

a is less than b

7. While Loops in Bash

A Loop allows you to run a series of commands a number of times until a particular condition is met. While loops execute a block of code over and over as long as the condition is met. As soon as the condition is no longer met, the loop exits.

Loops are very useful for automating repetitive tasks. Make sure that the condition is eventually met, or the loop will continue indefinitely for as long as the computer/server is on.

The basic syntax of a while loop is shown below:

while [CONDITION]
do
  [COMMANDS]
done

Let’s create a test-while.sh script file that will print the current value of the variable n and incremented by one.

nano test-while.sh

Add the following lines:

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

Save and close the file then run the script with the following command:

bash test-while.sh

The loop iterates as long as n is less than or equal to 5 and prints the following output:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

As soon as the condition is no longer met, the loop exits, and the program finishes executing.

8. For Loop in Bash

For loops in bash are also useful for automating repetitive tasks.

The basic syntax of a For Loop is shown below:

for item in [LIST]
do
  [COMMANDS]
done

For example, let’s create a test-for.sh script and use the for expression to specify a range of numbers or characters that we want to loop through.

nano test-for.sh

Add the following contents:

#!/bin/bash
for n in {1..10}
do
  echo "Number: $n"
done

Save and close the file, then execute the script with the following command:

bash test-for.sh

This will print the number from 1 to 10, as shown below:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10

The loop increments the variable until the condition is no longer met.

9. Read from a File in Bash

You can read any file line-by-line using a loop in a bash script.

First, create a file named file.txt with the following contents:

nano file.txt

Add the following lines:

Linux
Ubuntu
CentOS
Fedora
Debian

We’re going to use this file as our example file. Save and close the file, then create a test-file.sh script:

nano test-file.sh

Add the following lines:

#!/bin/bash
file='file.txt'
while read line; do
echo $line
done < $file

Save the file, then run the script that we just wrote using the following command:

bash test-file.sh

You should see the following output:

Linux
Ubuntu
CentOS
Fedora
Debian

10. Check If a File or Directory Exists

You can also check the existence of a file or directory using the -f and -d options in bash scripts.

For example, create a test-check.sh file and check whether the specified file exists or not.

nano test-check.sh

Add the following lines:

#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi

In this script, we also show you how to pass arguments to a script when calling it from the command line. You do so by setting a variable to $1 for the first argument.

Save the file, then run the script to check whether the /etc/fstab file exists:

bash test-check.sh /etc/fstab

You should see the following output:

File exists

Next, create another script named test-checkdir.sh and check whether the specified directory exists or not.

nano test-checkdir.sh

Add the following lines:

#!/bin/bash
dirname=$1
if [ -d "$dirname" ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi

Save and close the file, then check whether the /opt directory exists with the following command:

bash test-checkdir.sh /opt

You should get the following output:

Directory exists

Conclusion

These are just a few examples of some basic bash script concepts and syntax. You can combine these blocks and statements to create a more complex and useful script.

In the above guide, we showed you what bash scripts are, how they can be useful, and some bash script examples to help you get started with scripting.


You can use bash scripts to automate tasks, but having someone else do it for you saves you even more time and effort than writing a script. If you use one of our fully managed Linux web hosting solutions, you can simply ask our technical support to create a bash script to automate a task for you. Our experts can also help you just accomplish the task that you need instead of writing a script. They are available 24/7 and will help you with any aspect of managing your server.

If this post helped you learn about bash scripting, we would appreciate you sharing this post using our social media shortcuts. If you have any questions or comments, feel free to share them in the comments section below. Thank you.

1 thought on “Bash Script Examples”

  1. I often love to set defaults for shell variables, and allow them to be overridden by a command line set of “keyword=value”. Admittedly horribly fragile, and with getopt there are better –options, but you can hardly beat the simplicity?

    a=1
    b=2
    # simple keyword=value command line parser for bash
    for arg in $*; do\
    export $arg
    done

    #now use your variables
    echo a=$a b=$b

    Reply

Leave a Comment