Learn Complete Linux Bash Scripting in One Article

WORDS: 1515 | CODE BLOCKS: 27 | EXT. LINKS: 4

– Photo by Iván Rivero from Pexels

In this article I’ll be discussing about linux bash scripting (shell scripting) and I will cover every fundamental concept that you need to get started with bash scripting under linux environment.
Bash scripting is a critical skill for every programmer.

First of all you will need a linux machine to execute these scripts.
You can use any of the below techniques to get a linux machine:

  • Install a linux distribution
  • Install WSL
  • Install Cygwin or MSYS
  • Installing git for bash will provide a bash prompt but this prompt is not a complete linux environment

I’ll suggest you to install WSL2 with Ubuntu-2020.04 (same is installed on my machine).

This one article will cover all the basics and some advanced concepts about bash (shell) scripting, so read it completely.

Very Basics

1. Hello World

Every programmer start by writing a program to print ‘Hello World’ on the console.
Create a file named hello.sh and open it with your favourite text editor (notepad, sublime, atom, vscode, nano, vim, etc).
Write the following code into the file and save.

bash
1 echo "Hello World :)"

Now run the script by using following command

sh
1$ bash ./hello.sh

This will print

Hello World :)

2. Comments

We can write comments by using # symbol.

bash
1# This is a comment and will not be executed
2# The below command will print "Hello World" to the console
3echo "Hello World"

Hello World

3. What is shebang (#! /bin/bash)

The shebang is used if you run the script directly as an executable file (for example with the command ./script.sh ). In this case it tells the operating system which executable to run. It’s not required and has no effect if you for example write bash ./script.sh or source the script.
We write the below line at the top of every script #!/bin/bash or #!/usr/bin/env bash

Hello World with shebang
bash
1#!/usr/bin/env bash
2# hello.sh
3echo "Hello World :)"

Hello World :)

4. Variables

Creating variables in bash script is as simple as

bash
1name="Vikash"

NOTE: Remember there is no space around = operator.

Hello World with variables

hello2.sh

bash
1#!/usr/bin/env bash
2msg="Hello World from a variable"
3echo $msg

$ ./hello2.sh

Hello World from a variable

5. Command line arguments

We can pass arguments while executing the script and use them in the script.
A simple example is below.

params.sh

bash
1#!/usr/bin/env bash
2name=$1
3website=$2
4echo "Hello I am $name"
5echo "My website is $website"

$ ./params.sh "Vikash" "Villageprogrammer.blogspot.com"

Hello I am Vikash My website is Villageprogrammer

Parameter Name Description
$0 Script name and path
$1 First argument
$2 - $9 Second to ninth argument
${10} - ${…} More than tenth argument

You can execute a standard linux command and store the result in the variable. – params2.sh

bash
1#!/usr/bin/env bash
2today=$(date)
3directory=$(pwd)
4echo "Today is : $today"
5echo "Directory : $directory"

$ ./params2.sh

Today is : Thu Feb 18 17:05:56 IST 202 Directory : /mnt/d/Xplore-Training/UNIX/bash-scripting/scripting

Controls

1. If statement

The syntax of if statement is similar to other programming languages like C, C++.
Syntax

bash
1if [ condition ]
2then
3	# write your code here
4fi

Example:

if.sh

bash
1#!/usr/bin/env bash
2num=10
3if [ $num -lt 20 ]
4then
5	echo "$num is less than 20"
6fi

$ if.sh

10 is less than 20

You can combine parameter and variable logic with if to write complex scripts.

2. if-else

Syntax

bash
1if [ condition ]
2then
3	# write your code here
4else
5	# write your code here
6fi

Example:

if-else.sh

bash
1#!/usr/bin/env bash
2num=10
3if [ $num -eq 50 ]
4then
5	echo "$num is equal to 50"
6else
7	echo "$num is not equal to 50"
8fi

$ ./if-else.sh

10 is not equal to 50

3. if-elif-else

Syntax

bash
1if [ condition ]
2then
3	# write your code here
4elif [ condition ]
5then
6	# write your code here
7fi

Example:

if-elif-else.sh

bash
 1#!/usr/bin/env bash
 2num=10
 3if [ $num -eq 20 ]
 4then
 5	echo "$num is equal to 20"
 6elif [ $num -lt 20 ]
 7then
 8	echo "$num is less than 20"
 9else
10	echo "$num is greater than 20"
11fi

$ ./if-elif-else.sh

10 is less than 20

Looping

Repetition of a code block can be done using while loop and for loop.

1. while loop

Syntax

bash
1while [ condition ]
2do
3	# write your code here
4done

Example

while.sh

bash
1count=1
2while [ $count -lt 5 ]
3do
4	echo $count
5	((count++))
6done

$ ./while.sh

1 2 3 4 5

2. for loop

We can pass an array of elements from command line and use them in the script by creating an array array=$@ Syntax:

bash
1for num in $container
2do
3	echo $num
4done

Example:

for.sh

bash
1#!/usr/bin/env bash
2nums=$@
3for num in $nums
4do
5	echo $num
6done

$ ./for.sh 1 2 3

1 2 3

3. break and continue

break-continue.sh

bash
 1#!/usr/bin/env bash
 2# use '@' for entering more than one inputs (simply an array)
 3# Pass the values from command line arguments
 4names=$@
 5# use of break
 6for name in $names
 7do
 8    if [ $name = "Andy" ]
 9    then
10        echo "End found"
11        break
12    else
13        echo "Hello, $name"
14    fi
15done
16
17echo "for <break> loop terminated"
18# use of continue
19for name in $names
20do
21    if [ $name = "Andy" ]
22    then
23        echo "Skip found"
24        continue
25    else
26        echo "Hello, $name"
27    fi
28done
29
30echo "for <continue> loop terminated"
31exit 0

$ break-continue.sh "Vikas" "Andy" "Mark"

Hello, Vikas End Found for <break> loop terminated Hello, Vikas Skip found Hello, Mark for <continue> loop terminated

Working with environment variables

We can access any of the environment variable from the bash script.

vars.sh

bash
 1#!/usr/bin/env bash
 2# environment variables
 3
 4echo "The path is : $PATH"
 5echo "The terminal is : $TERM"
 6echo "The editor is : $EDITOR"
 7
 8# -z checks for empty
 9if [ -z $EDITOR ]
10then
11    echo "The Editor variable is empty"
12fi
13exit 0

$ ./vars.sh

The path is : <very long list of all paths will be printed> The terminal is : xterm-256color The editor is : The Editor variable is empty

Environment variables and their meaning

HOME : user’s home directory PATH : executable binary’s path HOSTNAME : hostname of the machine SHELL : shell that is being used USER : user of this session TERM : type of command line terminal that is being used

write a program to print user’s name, computer name, and home directory
bash
1echo "$USER@$HOSTNAME in [$HOME]"

vikas@DAVE in [/home/vikas]

Functions in bash

There are two ways to create functions in bash :

1. Function declaration syntax with function keyword

-function1.sh-

bash
1#!/usr/bin/env bash
2function greeting(){
3	echo "Hello"
4}

2. Function declaration without keyword

-function2.sh-

bash
1#!/usr/bin/env bash
2greeting(){
3	echo "Hello"
4}

3. Calling the function

To call the function we just need to use the name of the function, we do not use parentheses as we use in other programming languages (e.g. C, C++, Java, Python, etc.).
-function1.sh-

bash
1#!/usr/bin/env bash
2# declare the function
3function greeting(){
4	echo "Hello"
5}
6# calling the function
7greeting

$ bash ./function1.sh

Hello

4. What about passing parameters ?

It’s a two step process

  1. Access the parameter value To access the parameter use :
    $1: for first parameter,
    $2: for second parameter,
    … ,
    $n: for nth parameter.
    You can either create a local variable and save the value by local variable=$n or directly access the value by $n (n is the parameter number 1, 2, 3, etc).
  2. Pass the parameter value To pass the value write the value after the function name while calling the function (seperate by space). add 2 3

5. Complete example

-function.sh-

bash
 1#!/usr/bin/env bash
 2function add(){
 3	local num1=$1
 4	local num2=$2
 5	sum=`expr $num1 + $num2`
 6	echo "Sum=$sum"
 7}
 8
 9# call the function
10add 2 3 # 5
11add 4 5 # 9
12add -10 30 # 20
13# or use command line arguments (uncomment if used)
14# add $1 $2

$ bash ./function.sh

5 9 20

Working with prompt message

You can write a message when asking the user for input.
It can be done by using read command.

-user-prompt.sh-

bash
1#!/usr/bin/env bash
2read "Hey, What's your name ?" name
3echo "Hello, $name"

$ bash ./user-prompt.sh

Hey, What’s your name ? Vikash Hello, Vikash

If you want the input to be in the same line use -p..

-user-prompt2.sh-

bash
1#!/usr/bin/env bash
2read -p "Hey, What's your name ?" name
3echo "Hello, $name"

$ bash ./user-prompt2.sh

Hey, What’s your name ? Vikash Hello, Vikash


Now you have enough understanding to get started with bash (shell) scripting. Go ahead an read a book or two on bash scripting and you will be good at it.

Keep Learining, Keep Practicing. :) :)


That’s All. 😅

Thanks for reading. 🙏
If you liked it feel free to share with your dear ones.💗
And tell me what do you think in the comment box.💬

Stay tuned with CS111.

This post was originally posted on Village Programmer