Raspberry Pi_Eng_20.2.5 Execution Control of Script


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry

Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)

최신 라즈베리파이(Raspberry

Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


20.2.5  Execution Control of Script

 

20.2.5.1    Optional Processing according to Conditions

 

It is "if" statement and "case" statement to be used to selectively process commands depending on a certain condition.

 

   "if" statement

 

If the result of the specified conditional expression is "True", "if" statement executes the specified statements after "then", and if the result is "False", it executes the specified statements after "elif" or "else". The basic sysntax is as follows.

 

if         [conditional expression]

then

           execution statement

elif       [conditional expression]

then

           execution statement

else 

           execution statement

fi

if         [conditional expression] ; then

           execution statement

elif       [conditional expression] ; then

           execution statement

else 

           execution statement

fi

 

The reference value for determining "True" or "False" in the conditional expression is as follows.

    True            -- 0      -- zero             

    False           -- 1      -- non zero

 

The sentence starts with "if" and ends with "fi", and "elif" and "else" can be used optionally.

There must be spaces before and after conditional expressions. "if" and "then" must be separated by a semicolon (;) to put them on the same line. An execution statement can specify one or more statements.

 

If you want to use several conditional expressions other than the conditional expressions specified by "if", you can use "elif" statements selectively. If the result of the previous conditional expression is "False", the next "elif" statement is executed. When there is no additional "elif" statement, if "else" statement is present, the statement is executed, or the process ends.

 

[Used Example]

The following is a script processed selectively according to the value of input parameter. Input the following contents and save it into "/home/pi/Script/test.sh" file.

 

#!/bin/bash

if  [ $1 -eq 0 ]; then

           echo "correct number"  $1

else

           echo "wrong number"  $1

fi

 

If you run the above script as below, you can see how it is processed selectively.

 

pi@raspberrypi ~/Script $ ./test.sh 0

correct number 0

pi@raspberrypi ~/Script $ ./test.sh 4

wrong number 4

          

 

   "case" statement

 

"case" statement is a statement that can be used to process selectively according to a variable and the specified values.

 

case     $Variable   in

           A-value)

                      execution statement

                      ;;

           B-value)

                      execution statement

                      ;;

           *)

                      execution statement

                      ;;

esac

 

This statement starts with "case" and ends with "esac", and "value)" statement is optional. There is no limit to the number of "value)" to use, and "*)" means any value other than the value of all the "value)" specified earlier. An execution statement can specify more than one statement, and the last one must always end with ";;".

 

If the value of the variable is equal to the value specified in "value)" statement, then the specified statements are executed. If the value of the variable is not equal to the value specified in the earlier "value)" statement, it is passed to the next "value)" statement. If there is no match, the statement specified by "*)" is executed, and if there is no "*)", the process ends.

 

[Used Example]

The following is an example of executing a script using "case" statement. Input the following contents and save it into "/home/pi/Script/test_case.sh" file

 

#! /bin/bash

echo "input. Aa/Bb is correct"

read input

case $input  in

Aa)

           echo "OK." $input

           ;;

Bb)

           echo "OK." $input

           ;;

*)

           echo "Error." $input

           ;;

esac

exit 0

 

If you run the above script as below, you can see how it is processed selectively.

 

pi@raspberrypi ~/Script $ ./test_case.sh

input. AA/BB is correct

AA

OK. AA

pi@raspberrypi ~/Script $ ./test_case.sh

input. AA/BB is correct

AB

Error. AB

 

When you run the script, you will be prompted to enter a value. If you enter the required value and press [Enter] button, it determines if the entered value is correct and tells you the result.

20.2.5.2    Repetitive Processing

 

There are statements that can be used to repeat the same operation multiple times in the script, and those are "while", "until", and "for" statements. These sentences have the same basic processing, but these statements differ only in the manner to specify the conditional expression to determine whether to process and the logic to determine whether to process according to the results of the conditional expressions.

 

 

   "while" control statement

 

"while" statement continues processing when the result of the specified conditional expression is "True".

 

while  [ conditional expression ];

do

           execution statement

done

 

There must be spaces before and after conditional expression, and end with ";". The execution statement must be between "do" and "done", and multiple statements can be specified.

 

If the value of the conditional expression is "True", the next execution statement is processed. When the processing of the execution statement is completed, the conditional expression is checked again to check whether or not the processing continues. If the result of the conditional expression is "False", the process is terminated and the process proceeds to the next sentence.

 

[Used Example]

Create the following script and save it in "/home/pi/ Script/test_while.sh" file and prepare it to be executed.

 

#! /bin/bash

number =0

while [ number -le 4 ] ;

   do

           echo "number" $number

           number=$(( $number + 1 ))

   done

echo "All is completed"

exit 0

 

If you run the script as follows, you will notice that "while" statement is executed repeatedly while "number" is increased, and if the value is larger than 4, the processing is terminated.

 

pi@raspberrypi ~/Script $ ./test_while.sh

number 0

number 1

number 2

number 3

number 4

All is completed

 

 

   "until" control statement

 

This statement is a statement that continues processing when the result of the specified conditional expression is "False", that is, until the result of the specified conditional expression is "True".

 

until  [ conditional expressions ] ;

do

           execution statement

done

 

There must be spaces before and after Conditional expression, and end with ";". the execution statement must be between "do" and "done", and multiple statements can be specified.

 

If the value of the conditional expression is "False", the next execution statement is processed. When the processing of the execution statement is completed, the conditional expression is checked again to check whether or not the processing continues. If the result of the conditional expression is "True", the processing is terminated and proceed to the next sentence.

 

[Used Example]

This is almost similar to the one used in the previous "while" statement, but only changes the contents of the conditional expression.

 

#! /bin/bash

number =0

until [ number -gt 4 ] ;

   do

           echo "number" $number

           number=$(( $number + 1 ))

   done

echo "All is completed"

exit 0

 

When you run the script as follows, you see that "until" statement is executed repeatedly while "number" is increased, and if the value is larger than "4", the processing ends.

 

pi@raspberrypi ~/Script $ ./test_until.sh

number 0

number 1

number 2

number 3

number 4

All is completed

 

 

   "for" control statement

 

This statement is a statement that after the value of a variable starts with the initial value, continues processing when and the value of the conditional expression is "True", or when the value of the variable is within the specified range.

 

for (( Varialbe initialization;  conditional expression;  variable increment ))           

#          ex) for ((num=1; num<=10; num++))

 

do

           execution statement

done

for Varialbe  in  seq  initial-value  ending-value'                

#          ex) for num in 'seq 1 10'

do

           execution statement

done

for Varialbe  in Value1  Value2  Value3                      

#          ex) for num in 1 2 3 4 5 6 7 8 9 10

do

           execution statement

done

 

The value specified here must be a number and must be an integer. An increasing value is 1 if there is no special designation. Use "=" to set the initial value, and use operators such as "=", ">", ">=", "<", "<=", and "<>" to specify the conditional expression. The execution statement must be between "do" and "done", and multiple statements can be specified.

 

It starts from the initial value, processes the execution statement once, increases the value, and determines whether or not to process it. If the incremented value meets the specified condition or is not greater than the final value, continue processing. If the incremented value does not meet the specified condition or is greater than the final value, the processing is terminated.

 

[Used Example]

This is almost similar to the one used in the previous "while" statement, but only changes the contents of the conditional expression.

 

#! /bin/bash

for  (( number=0;  number <= 4;  number++  ))

   do

           echo "number" $number

done

echo "All is completed"

exit 0

 

If you run the script as follows, you will notice that "for" statement is executed repeatedly while "number" is increased, and if the value is larger than "4", the processing ends.

 

pi@raspberrypi ~/Script $ ./test_for.sh

number 0

number 1

number 2

number 3

number 4

All is completed