Shell Script - Basic [Part - 2]

Bash Scripting Cheat Sheet:
https://cheatography.com/danilobanjac/cheat-sheets/bash-scripting-language-cheat-sheet/

  1. if elif

  2. loops

  3. functions

    if elif

    #!/bin/bash

    #Defining Variables

    a=100
    b=200
    c=300

    #using if condition

    #Note: When you are using && and gt (AND , Greater then condtion, in that you need to use [[ ]] double quare bracket )

    if [[ $a -gt $b && $a -gt $c ]]
    then
    echo "A is biggest"
    elif [[ $b - gt $a && $b -gt $c ]]
    then
    echo "B is biggest"
    else
    echo "C isbiggest"
    fi

    Note: The comparison statement should be within the square bracket [] and there should be at least one space between the bracket and your statement and the values on either side.

    = (Equal to operator) should only be used to compare strings for numerical operations you can use -eg, -ne, gt, etc...

    For Loops

    for ((i=0; i<10; i++)) do echo "$i" ; done
    max=10 ; for (( i=2; i <= $max; ++i )) do echo "$i" ; done

    for i in {10..20}; do echo "$i"; done
    for i in 1 2 3 4 5; do echo "$i" ; done

    #!/bin/bash
    for j in `seq 1 10`
    do echo $j
    done

    • Create multiple files using touch
      touch file-{2..10}.txt

    • To list/iterate all the files within the Directory
      for FILE in * do echo $FILE done

    • To list/iterate only the file with end with .txt within the Directory

      for FILE in *.txt do echo $FILE done

    • Taking Input from a text file
      for i in $(cat input.txt) do echo $i done
      Or
      for i in `cat input.txt` do echo $i done

      While Loops

      • The syntax of a while loop in BASH is something like below:

          while [ condition ];
          do
              # statements
              # commands
          done
        
      • Creating a While Loop in Shell Script

        i=0
        while [ $i -le 10 ]

        do

        echo True

        ((i++))

        done

        echo False

      • Infinite While Loop in Shell Script

        while :; do echo Script ran $i times; ((i++)); done

Refer:- https://www.geeksforgeeks.org/bash-scripting-while-loop

Case Statements

Syntax:

        case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac

Syntax:
case $variable in
pattern-1)
commands;;

pattern-2)
commands;;
pattern-3)
commands;;
pattern-N)
commands;;
*)
commands;;
esac

Code:
#!/bin/bash
echo "Which color do you like best?"
echo "1 - Blue"
echo "2 - Red"
echo "3 - Yellow"
echo "4 - Green"
echo "5 - Orange"
read color;
case $color in
1) echo "Blue is a primary color.";;
2) echo "Red is a primary color.";;
3) echo "Yellow is a primary color.";;
4) echo "Green is a secondary color.";;
5) echo "Orange is a secondary color.";;
*) echo "This color is not available. Please choose a different one.";; esac

Functions

Function is a command in linux which is used to create functions or methods.
Function is a reusable block of code. Often we put repeated code in a function and call that function from various places. Library is a collection of functions. We can define commonly used function in a library and other scripts can use them without duplicating code.

When to us functions:
• Break up large script that performs many different tasks:
• Installing packages
• Adding users
• Configuring firewalls
• Perform Mathematical calculations

Bash Function Syntax

There are two different ways to declare a bash function:

1. The most widely used format is:

        <function name> () { 
                <commands> 
        }

Alternatively, the same function can be one line:

        <function name> () { <commands>; }

2. The alternative way to write a bash function is using the reserved word function:

        function <function name> {
                <commands>
        }

Or in one line:

        function <function name> { <commands>; }

Following example shows the use of the function −

        #!/bin/sh

        # Define your function here
        Hello () {
           echo "Hello World"
        }

        # Invoke your function
        Hello

function add() { sum=$(( $1 + $2 )) echo $sum } result=$(add 3 5) echo "The result is $result"

add_user()
{
USER=$1 #Argument 1
PASS=$2 #Argument1 2

useradd -m -p $PASS $USER && echo "Successfully added user"

}

#MAIN #Calling Function

add_user devops test123

Refer: https://phoenixnap.com/kb/bash-function

Arithmetic Operators

  • + (Addition)
    a=10 ; b=20 ; expr $a + $b

  • - (Subtraction)
    a=10 ; b=20 ; expr $a - $b

  • (Multiplication) :- The `should be escaped as*for multiplication usingexprstatement.a=10 ; b=20 ; expr $a * $b`

  • / (Division)
    a=10 ; b=20 ; expr $b / $a

  • % (Modulus)
    a=10 ; b=20 ; expr $b % $a

  • = (Assignment) :- Assigns the right operand to the left operand
    a=10 ; b=20 ; expr $b % $a

  • == (Equality) :- Compares two numbers, if both are the same then returns true.
    a=10 ; b=20 ; [ $a == $b ] ; echo $?

  • != (Not Equality) :- Compares two numbers, if both are different then returns true.
    a=10 ; b=20 ;[ $a != $b ] ; echo $?

    Note:- Make sure you have space before and after the Arithmetic Operators when using expr cmd.

Double parentheses:
echo $(( a + b )) echo $(( a-b )) echo $((a/b)) echo $(( a * b ))

Code 1:-
A=20 B=10 echo "Sum is $(( A + B))" echo "Difference is $(( A - B))" echo "Product is $(( A * B))" echo "Quotient is $(( A / B))"

Code 2:-
A=20
B=10

echo "Sum is $(expr $A + $B)"

echo "Difference is "$(expr $A - $B)

echo "Product is "$(expr $A * $B)

echo "Quotient is $(expr $A / $B)"

Code 3:-
num1=$1 num2=$2 num3=$3 sum=$(( num1 + num2 + num3 )) average=$(echo "$sum / 3" | bc -l) echo $average

Relational Operators

  • -eq :- Checks if the value of two operands is equal or not; if yes, then the condition becomes true.
    a=10 ; b=20 ; [ $a -eq $b ] ; echo $?

  • -ne :- Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ]

  • -gt :- Checks if the value of the left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ]

  • -lt :- Checks if the value of the left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ]

  • -ge :- Checks if the value of the left operand is greater than or equal to the value of the right operand; if yes, then the condition becomes true. [ $a -ge $b ]
    -le :- Checks if the value of the left operand is less than or equal to the value of the right operand; if yes, then the condition becomes true.
    [ $a -le $b ]

Boolean Operators

  • ! :- This is logical negation. This inverts a true condition into false and vice versa. [ ! false ] is true.

  • -o :- This is logical OR. If one of the operands is true, then the condition becomes true. [ $a -lt 20 -o $b -gt 100 ] is true.

  • -a :- This is logical AND. If both the operands are true, then the condition becomes true otherwise false. [ $a -lt 20 -a $b -gt 100 ] is false.

String Operators

  • = :- Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a = $b ] is not true.

  • != :- [Not Equal to] Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true. [ $a != $b ] is true.

Special Variables

$0 :- The filename of the current script.

$n :- These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).

$# :- The number of arguments supplied to a script.

$ :- All the arguments are double quoted. If a script receives two arguments, $\ is equivalent to $1 $2.

$@ :- All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.

$? :- The exit status of the last command executed.

$$ :- The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

$! :- The process number of the last background command.

Few Shell Substitutions:

Note:- -e option enables the interpretation of backslash escapes.

a=10 ; echo -e "Value of a is $a \t .... \t ... \v ...."

\v vertical tab
\t horizontal tab
\n new line

Conditional Operators

Double Square Brackets:-

AND and OR Operators

File Operators

Conditional Statements:
There are total 5 conditional statements that can be used in bash programming

  1. if statement

  2. if-else statement

  3. if..elif..else..fi statement (Else If ladder)

  4. if..then..else..if..then..fi..fi..(Nested if)

  5. switch statement

Their description with syntax is as follows:

if statement
This block will process if the specified condition is true.
Syntax:

if [ expression ]
then
   statement
fi

if-else statement
If the specified condition is not true in if part then else part will be execute.
Syntax

if [ expression ]
then
   statement1
else
   statement2
fi

if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
Syntax

if [ expression1 ]
then
   statement1
   statement2
   .
   .
elif [ expression2 ]
then
   statement3
   statement4
   .
   .
else
   statement5
fi

if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check.
Syntax:

if [ expression1 ]
then
   statement1
   statement2
   .
else
   if [ expression2 ]
   then
      statement3
      .
   fi
fi

Switch statement
case statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.

Syntax:

case  in
   Pattern 1) Statement 1;;
   Pattern n) Statement n;;
esac

Exit Codes

When a script or process exits or is terminated by some other means, it will have an exit code, which gives some indication about how or why the script or process ended.
For example, an exit code of 0 means that the process exited without error – in other words, it completed its task and exited as expected. On the other hand, an exit code of 1 means that the process encountered some kind of error upon exiting.

How to get the exit code of a command
You need to use a particular shell variable called $? to get the exit status of the previously executed command.

i.e
date echo $? date-foo-bar printf '%d\n' $?

How to use exit codes in scripts

Syntax:

exit [n]

To use exit codes in scripts an if statement can be used to see if an operation was successful.

#!/bin/bash

cat file.txt 

if [ $? -eq 0 ]
then
  echo "The script ran ok"
  exit 0
else
  echo "The script failed" >&2
  exit 1
fi

Additional :
-n string is not null.
-z string is null, that is, has zero length

  • You can use the below Tools while working on your scripting/coding