[Bash] Shell Scripting in Linux Hands-On

·

9 min read

[Bash] Shell Scripting in Linux Hands-On

What is shell scripting?

Shell Scripting is a program to write a series of commands for the shell to execute or simply we can say that shell scripting is writing a bunch of command and executing them from shell itself.

Shell: A shell is a computer program that presents a command line interface which allows you to control your computer using commands entered with a keyboard instead of controlling graphical user interfaces (GUIs) with a mouse/keyboard/touchscreen combination.

Script: A script is a program or sequence of instructions that is interpreted or carried out by another program.

Type of Shells:

Depending on different OS there are different type of shells. To check type of shells offered by your OS just type:

cat /ect/shells

image.png

To check path of your Shell

which bash

image.png

Bash: Bourne-Again Shell

Dash: Debian Almquist shell

rbash: If Bash is started with the name rbash , or the --restricted or -r option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell.

Let's make our first shell script

Just open your Terminal and follow the steps:

Simply type in terminal:

touch hello.sh

Now, open this file with any editor here I am using VsCode but you can use any IDE according to your preference.

Now, from here we will be writing the commands in our hello.sh file.

  • before starting with your shell script file always specify the path of your shell (in my case I am using bash so I am specifying bash path followed by #!)

Printing Hello-World using hello.sh

  • #! /bin/bash
    
  • declaring comments using #
    # it is a comment
    
  • printing hello-world using
    echo "Hello-World"
    
  • Now save the changes in hello.sh script

    #! /bin/bash 
    # it is a comment
    echo "Hello-World"
    

    and run the script file in terminal using

    ./hello.sh
    
  • image.png

System defined variables

  • Build-in or system defined variables will always be in Capital letters i.e BASH, HOME and variables will always be called after $
    echo Our shell is: $BASH #give bash shell name
    echo Our shell version is: $BASH_VERSION
    echo Our home directory is: $HOME
    echo Our current working directory is: $PWD
    
  • image.png

Declaring global variables

  • NOTE: there variables can be called globally
    name=Mark
    echo The name is: $name
    value=10
    echo The value is: $value
    
  • image.png

Taking input from user for variables

  • echo "Enter names: "
    read n1 n2 n3 n4
    echo "Names: $n1,$n2,$n3,$n4"
    
  • image.png

Taking silent input and in same line

  • -p for taking input in same line -s for taking silent input i.e data will not be visible while inserting
    read -p "username: " u_name
    read -sp "password: " pass 
    echo 
    echo "username: $u_name"       
    echo "password: $pass"
    
    image.png

Declaring arrays

  • -a for array @ for printing all values of array
    echo "Enter names: "
    read -a name
    echo Names are : ${name[@]}
    
    image.png
  • Printing specific values of array
    echo "Enter names: "
    read -a name
    echo "Names are : ${name[0]}, ${name[1]}"
    
    image.png
  • Printing index of array

    echo "Enter names: "
    read -a name
    echo Index of array : ${!name[@]}
    

    image.png

  • Printing length of array

    echo "Enter names: "
    read -a name
    echo Length of array is : ${#name[@]}
    

    image.png

  • Adding values to array

    os=('ubuntu' 'windows' 'mac')
    os[3]='kali'         #--> setting value
    echo Array is : ${os[@]}
    

    image.png

  • Removing values from array
    os=('ubuntu' 'windows' 'mac')
    unset os[2] #--> remove value from 2nd index
    os[3]='kali' #--> setting value
    echo Array is : ${os[@]}
    
    image.png

Reading input by default variable

  • By default data value will be stored in a default variable REPLY
    echo "Enter name: "
    read 
    echo "Name is : $REPLY"
    
    image.png

Taking input as argument

  • echo Names are : $1 $2 $3
    
    image.png Alternate method
    args=("$@") #arguments as an array
    echo Names are : $@
    
    image.png

if statement

  • -ne for not equal comparison fi for telling system that if statement ends here.
    count=10
    if (( $count == 1 ))
    # or if [ $count -eq 10 ]
    then
      echo "equal"
    elif [ $count -ne 1 ]
    then 
      echo "not equal"
    else
      echo "Invalid"
    fi         #--> to specify end of if statement
    
    image.png Here is the list of specifying operators in shell scripting image.png

File/Folder test operators

  • Before executing the below code make sure that you have created some files/folders. -e for taking input in same line -f for checking there is file or not -w for checking write permissions cat >> for inserting and appending data.
    echo -e "Enter the name of the file : \c"
    read file_name
    if [ -e $file_name ] # -e for exist or not
    # -f for it is file or not
    # -d for it is directory or not
    # -s for file is empty or not
    then 
      echo "$file_name found"
    else
      echo "$file_name not found"
    fi
    
    In my case I have a file as hi image.png

Inserting/Appending data to file

  • echo -e "Enter the name of the file : \c"
    read file_name
    if [ -f $file_name ]
    then 
      if [ -w $file_name ]
      then
          echo "type some text data. Press ctrl+d to exit."
          cat >> $file_name
      else
          echo "File don't have write permissions."
      fi
    else
      echo "$file_name not found"
    fi
    
    Before moving ahead you have to make sure that you have a file to enter some data and the file mush have write permissions. To check write permissions just type ls -la image.png If your file don't have any write permissions to that file just type chmod +w <file_name> Now executing the bash file image.png Even if you try to add text again the text will not be overwritten rather it will be appended to the file image.png image.png

switch case

  • echo Hey choose an option
    echo
    echo a=To see current date
    echo b=list all the files in current dir
    echo -e "Enter choice : \c"
    read choice
    case $choice in
      a) date;;
      b) ls;;
      *) echo "Invalid output" 
    esac   #--> specifying end of switch case
    
    image.png pattern based case
    echo -e "Enter some character : \c"
    read value
    case $value in
      [a-z] )
          echo "a-z";;
      [A-Z] )
          echo "A-Z";;
      [0-9] )
          echo "0-9";;
      ? )
          echo "specical char";;
      * )
          echo "invalid"
    esac
    
    image.png

for loop

  • Method 1
    for i in 1 2 3 4 5
    do 
      echo the number is $i
    done
    
    Method 2
    for j in eat your lunch 
    do echo $j
    done
    
    Method 3
    for p in {1..10..2} # {start..end..increment}--> not work in version less than 4
    do echo $p
    done
    
    Method 4
    for (( i-0; i<5; i++ ))
    do 
      echo $i
    done
    
    for loop to execute command
    for command in ls pwd date
    do  
      echo -------------$command------------  #--->printing command
      $command    # --->running command
    done
    
    printing folders from for loop
    for i in *
    do
      if [ -d $i ]  #---> -d for folders and -f for files
      then
          echo $i
      fi
    done
    
    iterating values from file ; hosts is the path of file including file_name at last i.e where I have written hi
    hosts="/home/shankar/Desktop/shell_script/hi"
    for i in $(cat $hosts)
    do echo $i
    done
    

while loop

  • count=0
    num=10
    while [ $count -le $num ]  # ---> -le for less than equal to
    do 
      echo Numbers are $count
      let count++
    done
    

select loop

  • select name in mark john ben julie
    do 
      case $name in 
      mark ) echo "mark selected" ;;
      john ) echo "john selected" ;;
      ben ) echo "ben selected" ;;
      julie ) echo "julie selected" ;;
      * ) echo "invalid" ;;
      esac
    done
    

until loop

  • n=0
    until [ $n -ge 10 ]
    do 
      echo $n
      n=$(( n+1 )) ## or let n++
    done
    
    image.png

Logical Operators

  • AND operator -gt for greater than -lt for less than && or -a for AND logical operator
    a=6
    if [ $a -gt 5 ] && [ $a -lt 7 ]
    then
      echo "true"
    else
      echo "false"
    fi
    
    image.png OR operator || or -o for OR logical operator
    a=1
    if [ $a -gt 5 ] || [ $a -lt 7 ]
    then
      echo "true"
    else
      echo "false"
    fi
    
    image.png

Arithmetic operators

  • a=20
    b=10
    echo $(( a+b ))
    echo $(expr $a - $b )     #-->alternate way
    echo $(( a/b ))
    echo $(( a*b ))
    echo $(( a%b ))
    
    image.png floating point operations bc for basic calculation in float scale is the number of values after decimal point -l for calling math library
    n=2.5
    m=4.4
    echo "$n+$m" | bc
    echo "$n-$m" | bc
    echo "$n*$m" | bc
    echo "scale=2;$m/$n" | bc
    echo "$m%$n" | bc
    num=4
    echo "scale=2;sqrt($num)" | bc -l   #--> -l for calling math library
    echo "3^3" | bc  -l
    

Reading a file's content

  • Put file name in place of hi Method 1
    while read p
    do echo $p
    done < hi
    
    image.png Method 2
    cat hi | while read p
    do echo $p
    done
    
    Method 3 -r for mentioning end of line
    while IFS=' ' read -r line 
    do
      echo $line
    done < hi
    

Functions

  • Method 1
    function greet(){
      echo "Hello-World"
    }
    greet  # --> calling function
    
    image.png Method 2
    name(){
      echo $1
    }
    name Ram  # --> calling function
    
    image.png

Declaring local variables

  • while declaring function the variable we use are global i.e can be used outside the function but sometime we don't want such behavior so we define local variables followed by local keyword.
    id(){
          local name=$1
          echo $name
    }
    name=Ram
    echo names is $name before
    id Ben
    echo names is $name after
    
    image.png

Declaring readonly variables

  • after making variables readonly you would not be able to change its value
    var=31
    readonly var
    var=50 
    echo var is : $var
    
    image.png

Declaring readonly functions

  • after making function readonly we will not be able to overwrite this function
    hello(){
          echo Hello guys
    }
    readonly -f hello  #--> -f for function
    hello
    
    image.png

Signal and Trap

  • trap "echo file deleted" 0 2 15
    echo "pid is $$"   
    while (( COUNT < 10 ))
    do
      sleep 1
      (( COUNT ++ ))
      echo $COUNT
    done
    exit 0
    
    image.png

Debugging

  • Method 1
    bash -x ./hello.sh
    
    Method 2
    set -x    #--> from
    echo hi  #--> script
    set +x   #--> to
    

That's it You are now done with shell scripting. Hope the above information was valuable to you.