What is Bash Script Examples?

If you have prior coding experience then getting along with the bash script will be easier for you. This blog post, What is Bash Script will give you a brief understanding about bash scripting.

Updated: 01 Jun, 23 by Susith Nonis 9 Min

List of content you will read in this article:

Shell is a unique program that acts as an interface where the user can interact with the kernel with the help of human-readable commands. Then the commands will get converted to a language that is understandable by Kernel. In Linux, a shell will take the command input from the users and process it to display the output on the screen. Linux allows you to access Shell using command-line.

BASH shell is a command-line interpreter for most of the Linux distributions by default. As a Linux system administrator, you need to have strong knowledge of BASH shell commands. Using BASH scripting, you will be able to automate various repetitive tasks that will help in reducing manual tasks. Such scripts are called shell scripts. 

For creating, running, and executing bash shell scripts, you can follow the below-mentioned simple steps-

  • Creating a file with the help of a text editor with .sh extension
  • Starting the script with #!/bin/bash
  • Writing basic code or commands
  • Saving the script file as the filename.sh

Below we have mentioned some of the basic ideas of getting along with the BASH shell scripting. We have some examples explaining how the BASH scripts are being created.

1.   Basic “Hello World” program

It is one of the common test programs that programmers try to run to test all the work. You can use either vim or nano editor for creating a file “helloworld.sh”.

$ nano helloword.sh

Now, you can type or copy the below line in the “helloworld.sh” file and then save it.

#!/bin/bash

echo "Hello World"

Now, to run the program, you can run the following command.

$ bash helloworld.sh

You can try another method by adding the execute permission to the “helloworld” file as shown below.

$ chmod a+x helloworld.sh

Once the file has the execute permission, you can now run the file using the below command.

$ ./helloworld.sh

Output-

Hello World

2.   Echo command examples

It is one of the commonly used commands that allows the users to print the text or output on the screen. This command comes with various options for different functionality. You can use the following syntax for the echo command.

echo [options] [ARGUMENTS]

Available Options-

  • -n is used for suppressing the trailing newline
  • -e is used for interpreting the backslash-escaped characters
  • -E is used for disabling the interpretation of the escape characters, and it is considered to be the default option for the echo command.

For creating a bash file, use the below code of line.

#!/bin/bash

echo "BASH"

echo -n "Linux User"

echo -e "\nHello \t Jim \t Tim"

In the above command, you can see the “\‘n” (escape character) for specifying the new line and “\t” for specifying the horizontal tab. 

Output-

BASH

Linux User

Hello Jim Tim

3.   Using comments

Comments are being used by the programmers to add some information or detail about the specific code of line explaining what it will do. The comment part will get ignored by the compiler while processing the code. The comment starts with “#” character at the starting of the line. 

Example-

# this is a sample comment.

Comments are of two types-

  • Single line comment
  • Multiple line comment

For specifying the single line command, you need to use “#” and for specifying the multiple line comment, you need to use :’.

Example-

#!/bin/bash

: '

This is the first line

Comment extended.

'

((add =2+8))

# display result 

echo "Add is $add"

Output-

Add is 10

4.   Using variables

Variables are the named symbols that are basically used for storing the values temporarily. These variables can be a string or numeric. At any time, you can create variables and assign them values. Bash has three types of variables that are listed below.

Special variables-

  • $#: it will specify the number of command-line parameters that you have passed to the script.
  • $@: it will specify all the parameters sent to the script.
  • $?: it will specify the end status of the last process to execute.
  • $$: it will specify the current script’s Process ID.
  • $USER: it will specify the particular user who is executing the script.
  • $HOSTNAME: it will specify the machine’s hostname on which the script is executing.
  • $SECONDS: it will specify the number of seconds for which the script has been running.
  • $RANDOM: it will return the random number.
  • $LINENO: it will return the script’s current line number.

Environment variables-

You can use the following command to check the active environment variables in your bash.

env | less

Output:

User-defined variables-

These types of variables are defined by users within the scripts. In the below example, we have a variable “var” that will store a value.

var=2020

And to refer to this variable we will use “$” as shown below.

echo $year

you can see that we used $  to reference its value.

5.   Getting user input

You can allow the user to provide the input for making a script interactive, for taking the input we will use the “read” command.

Example-

#!/bin/bash

echo "Enter the year"

read year

echo "Your year is $year"

Output-

Enter the year

2021

Your year is 2021

6.   Using command arguments 

In bash, you will be able to read user inputs from the command arguments. These arguments can be used within the scripts. In the below example, we have mentioned various arguments.

Example-

#!/bin/bash

echo "Total number of arguments : $#"

echo "User_name: $1"

echo "User_age: $2"

echo "Full_Name: $3"

For providing inputs to these arguments, you can run the below command with the values for the arguments in a specific order.

$ bash arguments.sh Jim 30 'Linux'

Output-

Total number of arguments : 3

User_name: Jim

User_age: 30

Full_Name: Linux

7.   Using loops 

You can use loops whenever you want to run a specific code repetitively. Bash supports “while” and “for” loops.

While loop

If you want your code to be repeated an unknown number of times until the specified condition is satisfied. You can consider the below-mentioned examples.

The syntax for while loop:

#!/bin/bash

while [CONDITION]

do

  [COMMANDS]

done

In this case, the condition will be evaluated before running the command and will keep on executing the command until the condition evaluates to false. After that, the specific loop will get terminated.

Example-

#!/bin/bash

i=1

while [ $i -le 4 ]

do

  echo Num: $i

  ((i++))

done

Output-

Num: 1

Num: 2

Num: 3

Num: 4

For loop

You can use the “for” loop for iterating over a specified number of items and perform various mentioned commands. 

Syntax of for loop:

#!/bin/bash

for item in [LIST]

do

  [COMMANDS]

done

8.   Using conditional statements

These conditional statements will allow you to make decisions based on a specific condition. We have conditional blocks that are commonly used in bash scripts.

If statement

First, the condition will be evaluated, if the condition is true then the command will run. If the specified condition is not true then the following command will get ignored and the loop will end there.

Syntax-

if Condition

then

  STATEMENTS

fi

Example-

#!/bin/bash

echo -n "Enter number: "

read VAR

if [[ $VAR -gt 10 ]]

then

  echo "The number is greater than 10."

fi

If else statement

In this type of loop, if the specified condition is true then the following command will get executed otherwise the else block will get executed.

Syntax-

if Condition

then

  STATEMENTS1

else

  STATEMENTS2

fi

Example-

#!/bin/bash

echo -n "Enter number: "

read VAR

if [[ $VAR -gt 10 ]]

then

  echo "The number is greater than 10."

else

  echo "The number is equal or less than 10."

fi 

If elif statement

It is useful if you want to check for more than one condition.

Syntax-

if Condition1

then

  STATEMENTS1

elif Condition2

then

  STATEMENTS2

else

  STATEMENTS3

fi

Example-

#!/bin/bash

echo -n "Enter number: "

read NUM

if [[ $NUM -gt 10 ]]

then

  echo "The number is greater than 10."

elif [[ $NUM -eq 10 ]]

then

  echo "The number is equal to 10."

else

  echo "The number is less than 10."

fi

9.   Using functions 

Using functions, you will be able to create customized code blocks which can be reused in various programs.

Syntax- 

function FunctionName()

{

  statements

}

Example-

#!/bin/bash

function Add()

{

  echo -n "Enter a: "

  read a

  echo -n "Enter b: "

  read b

  echo "Addition is: $(( a+b ))"

}

Sum

Output-

Enter a: 10

Enter b: 10

Addition is: 20

10.  Display string length

Bash provides various string functions and one of them is getting the length of the string. 

Example-

#!/bin/bash

Str1="Welcome"

echo "Length is: ${#Str1}"

Output-

Length is: 7

If you have prior coding experience then getting along with the bash scripting will be easier for you. As it provides concepts similar to any other programming language, all you need is to understand the logic that you want to implement. Whether you are a beginner or experienced, you can easily learn the syntax for bash scripting.

In this article, you will find the very basic commands along with their syntax and easy-understandable examples so that you can easily understand the working of the specific commands. 

Susith Nonis

Susith Nonis

I'm fascinated by the IT world and how the 1's and 0's work. While I venture into the world of Technology, I try to share what I know in the simplest way with you. Not a fan of coffee, a travel addict, and a self-accredited 'master chef'.