Getting started with Shell Scripting (2)

Time:2020-2-26

Today we’ll learn about shell operators and process control.

operator

Shell, like other programming languages, supports a variety of operators, including:

  • Arithmetic operator
  • Relational operators
  • Logical operators
  • String operator
  • File test operators

Let’s take a look.

Arithmetic operator

Native bash does not support simple mathematical operations, so it needs to use expr command.

For example, output the sum of two numbers:

sum=`expr 1 + 1`
echo $sum

Be careful:

Operands and operators must be separated by spaces;

Expressions must be wrapped in back quotes;

Operator Explain Example
+ addition expr 1 + 1
subtraction expr 1 – 1
* multiplication expr 1 \1 need to escapeNumber
/ division expr 1 / 1
% Remainder expr 2 % 2

The complete example is as follows:

a=1
b=2
Addition of Chinese Herbs
val=`expr $a + $b`
echo "$a+$b=$val"

Subtraction
val=`expr $a - $b`
echo "$a-$b=$val"

Multiplication
Val = ` expr $a \ * $B '-- must escape
echo "$a*$b=$val"

Division method
val=`expr $a / $b`
echo "$a/$b=$val"

Remove the surplus
val=`expr $a % $b`
echo "$a%$b=$val"

Relational operators

Relational operators are mathematical size relationships that compare two operands, supporting numbers and numeric strings (such as “1”)

operator Explain Example
-eq Check whether two numbers are equal [ $a -eq $b ]
-ne Check whether two numbers are different [ $a -ne $b ]
-gt Check whether the left side is greater than the right side [ $a -gt $b ]
-lt Check if the left side is less than the right side [ $a -lt $b ]
-ge Check whether the left side is greater than or equal to the right side [ $a -ge $b ]
-le Check whether the left side is less than or equal to the right side [ $a -le $b ]
== Judge whether two numbers are equal [ $a == $b ]
!= Judge whether two numbers don’t want to wait [ $a != $b ]

The following is an example of if comparison. If syntax will be studied in detail when this article introduces process control.

a=10
b=20

if [ $a -eq $b ]
then
    echo "$a=$b"
else
    echo "$a!=$b"
fi

Logical operators

Logical operators are and, or, not.

operator Explain Example
! Logical non [! False] returns true
-o Logic or [ $a -gt 0 -o $b -gt 0]Returns true when a and B have one greater than 0
-a Logic and [ $a -gt 0 -a $b -gt 0]Returns true when both a and B are greater than 0

Here is an example of combining relational operators:

a=1
b=2

if [ $a != $b ]
then
    echo "1!=2"
else
    echo "1=2"
fi

if [ $a -gt 0 -o $b -gt 0 ]
then
    Echo "a or B is greater than 0"
else
    Echo "a and B are not greater than 0"
fi

if [ $a -gt 0 -a $b -gt 0 ]
then
    Echo "a and B are greater than 0"
else
    Echo "a and B are not greater than 0"
fi

String operator

Shell is commonly used to process string data, so there are some operators that are specific to strings.

operator Explain Example
= Check if two strings are equal [ $a = $b ]
!= Check if two strings don’t want to wait [ $a != $b ]
-z Check if the string length is 0 [ -z $a ]
-n Check if the string length is not 0 [ -n $a ]
$ Check if the string is empty [ $a ]

Here are some examples:

a="hello"
b="world"

if [ $a = $b ]
then
    Echo "$a is the same as $B"
else
    Echo "$a is different from $B"
fi

if [ -z $a ]
then
    Echo "$a length is 0"
else
    Echo "$a length is not 0"
fi

if [ -n $a ]
then
    Echo "$a length is not 0"
else
    Echo "$a length is 0"
fi

if [ $a ]
then
    Echo "$a is not empty"
else
    Echo "$a is empty"
fi

File test operators

File test operators are used to detect various states of a file. The following table lists the commonly used file test operators.

Operator Explain Example
-d file Check if the file is a directory [ -d $file ]
-f file Check whether the file is a normal file (not a directory or a block device file) [ -f $file]
-r file Check whether the file is readable [ -r $file ]
-w file Check whether the file is writable [ -w $file ]
-x file Check if the file is executable [ -x $file ]
-s file Check if the file size is 0 [ -s $file ]
-e file Check if the file or folder exists [ -e $file ]
-S Check whether the file is a socket file [ -S $file ]
-L Check if the file exists and is a symbolic link [ -L $file ]

Here are some examples:

file="/etc/passwd"

if [ -d $file ]
then
    Echo "$file is the directory"
else
    Echo "$file is not a directory"
fi

if [ -f $file ]
then
    Echo "$file is a normal file"
else
    Echo "$file is not a normal file"
fi

if [ -e $file ]
then
    Echo "$file exists"
else
    Echo "$file does not exist"
fi

Process control

Shell’s process control also includes judgment and loop. Let’s learn about it.

if/else

grammar

if condition
then
     Statement 1
     Statement 2
     ...
     Statement N
elif condition2
then
     Statement 1
     Statement 2
     ...
     Statement N
else
     Statement 1
     Statement 2
     ...
     Statement N
fi
  • Elif and else branches can be omitted
  • If / FI needs pairing

Here are some examples:

a=1
b=2
if [ $a == $b ]
then
   echo "a = b"
elif [ $a -gt $b ]
then
   echo "a > b"
elif [ $a -lt $b ]
then
   echo "a < b"
else
   Echo "all conditions do not match"
fi

For cycle

The syntax is as follows

for item in item1 item2 ... itemN
do
    Statement 1
    Statement 2
    ...
    Statement N
done
  • Do / done needs pairing
  • In lists support file lists, strings, numbers, and other array data

Here is the loop output/etcAn example of the following files and directories:

for dir in `ls /etc`
do
    echo "$dir"
done

while

The syntax is as follows

while condition
do
    Statement 1
    Statement 2
    ...
    Statement N
done

Here is an example

c=1
while(( $c<=10 ))
do
    echo $c
        c=`expr $c + 1`
done

switch

The syntax is as follows

Case value in
Mode 1)
    Statement 1
    Statement 2
    ...
    Statement N
    ;;
Mode 2)
    Statement 1
    Statement 2
    ...
    Statement N
    ;;
*)
    Statement 1
    Statement 2
    ...
    Statement N
    ;;
easc
  • No other pattern statements will be executed after pattern matching (no manual break required)
  • Case / EASC must be paired
  • Two semicolons must be added at the end of each pattern statement
  • Use * to capture other modes

Here is an example

Echo 'enter day of week'
read day
case $day in
    1)
        Echo "Monday"
        ;;
    2)
        Echo "Tuesday"
        ;;
    ...
    *)
        Echo "invalid number entered"
        ;;
  • Read is to read a line from standard input and assign it to the specified variable

break

The break command allows you to jump out of the loop body. Here is an example

sum=0

while read n
do
    if [ $n -gt 0 ]
    then
        sum=`expr $sum + $n`
    else
        break
    fi
done

continue

The continue command allows you to skip this cycle and proceed directly to the next cycle. Here is an example

sum=0

while read n
do
    if [ $n -gt 0 ]
    then
        sum=`expr $sum + $n`
    else
        Continue ා this input is illegal, skip,
    fi
done

multiplication table

Combined with what we have learned today, we use shell to print a multiplication table:

#!/bin/bash

i=1

while [ $i -le 9 ] # i <= 9
do
    j=1
    while [ $j -le 9 ] # j <= 9
    do
        if [ $i -ge $j ] # if($i >= $j)
        then
            val=`expr $i \* $j`
            echo -n "$j*$i=$val "
        fi
        j=`expr $j + 1` # j++
    done
    echo
    i=`expr $i + 1` # i++
done

The results are as follows:

1*1=1 
1*2=2 2*2=4 
1*3=3 2*3=6 3*3=9 
1*4=4 2*4=8 3*4=12 4*4=16 
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 

Today’s content is the most important and commonly used syntax in shell. The next article will learn about the input and output of the shell.

Getting started with Shell Scripting (2)

(to be continued)