Shell process control

Posted by Nabster on Fri, 01 May 2020 06:24:57 +0200

Shell process control

if else

if statement

Syntax:

if condition
then
    command
    ...
fi

eg:

#!/bin/bash

a=100
b=100

if [ $a == $b ]
then
    echo "$a == $b"
fi

Output:

100 == 100

You can also write a line at the terminal:

[zhang@localhost ~]$ a=100
[zhang@localhost ~]$ b=100
[zhang@localhost ~]$ if [ $a == $b ]; then    echo "$a == $b"; fi
100 == 100

if else statement

Syntax:

if condition
then
    command
    ...
else
    command
    ...
fi

eg:

Input at terminal

[zhang@localhost ~]$ a=100
[zhang@localhost ~]$ b=200
[zhang@localhost ~]$ if [ $a == $b ]
> then
>     echo "$a == $b"
> else
>     echo "$a != $b"
> fi
100 != 200

if elif else statement

Syntax:

if condition1
then
    command1
    ...
elif comdition2
then
    command2
else
    command
fi

eg:

#!/bin/bash

a=100
b=200
c=150

if [ $[a + c] > $b ]
then
    echo "$a + $c > $b  return true"
elif [ $[a + c] < $b ]
then 
    echo "$a + $c < $b  return true"
else
    echo "$a + $c = $b  return true"
fi

Output results:

100 + 150 > 200  return true

for loop

for syntax:

for var in item1 item2 ... itemn
do
    command1
    command2
    ...
    commandn
done

Write in one line:

for var in item1 item2 ... itemn; do command1;command2 ... done;

eg:

[zhang@localhost ~]$ for num in 1 2 4 8 16
> do
>     echo $num
> done
1
2
4
8
16

One line execution:

[zhang@localhost ~]$ for num in 1 2 3 4 5; do echo $num; done
1
2
3
4
5

While statement

while syntax:

while condition
do
    command
done

eg:

#!/bin/bash

num=1

while(($num<=5))
do
    echo $num
    let "num++"
done

Output results:

1
2
3
4
5

Infinite cycle

while :
do
    command
done

perhaps

while true
do
    command
done

perhaps

for (( ; ; ))

until loop

until syntax:

until condiion
do
    command
done

Generally use while instead

case

case syntax:

case value in
value1)
    command1
    command2
    ...
    commandn
    ;;
value2)
    command1
    command2
    ...
    commandn
    ;;
value3)
    command1
    command2
    ...
    commandn
    ;;
*)
    command1
    command2
    ...
    commandn
    ;;
esac

;;;: during which all command s are executed to;; end. Equivalent to break.

*: equivalent to default in java.

eg:

#!/bin/bash

value=2

case $value in
1)
    echo "$value equal 1"
    ;;
2)
    echo "$value equal 2"
    ;;
3)
    echo "$value equal 3"
    ;;
*)
    echo "$value not find"
    ;;
esac

Output results:

2 equal 2

Jump out of the loop

break command

#!/bin/bash

for i in 1 2 3 4 5
do
   if [ $[i % 2] == 0 ]
   then
        echo "$i"
        break
   fi
done

Output: 2

continue command

#!/bin/bash

for i in 1 2 3 4 5
do
    if [ $[i % 2] == 0 ]
    then
        echo "$i"
        continue 
    fi
done

Output:

2
4

esac command

Use with case as the end symbol of case.

Topics: shell Java