Get the App
SLTechnology News&Howtos  ›  Servers  › 

Example of Linux Shell process control statement

Shulou Source: shulou.com Published: 2022-06-02 05:06:36 10月11日 Update

Author: Cheng Mo,

www.cnblogs.com/chengmo/archive/2010/10/14/1851434.html

The Linux shell has its own set of flow control statements, including conditional statements (if), loop statements (for,while), and select statements (case). Below I will introduce the following examples, the use of each statement method.

1. Shell conditional statement (if usage)

if statement structure [if/then/elif/else/fi]

if conditional test statement

then

action

[elif conditions

action

else

action

]

fi

If you are not clear about: conditional test statements, you can refer to: linux shell logical operators, logical expressions

Shell commands can be separated by semicolons or newlines. If you want to write more than one command on a line, you can split it by "';".

[chengmo@centos5 ~]$ a=5;if [[ a -gt 4 ]] ;then echo 'ok';fi;

ok

Example: (test.sh)

#!/ bin/sh

scores=40;

if [[ $scores -gt 90 ]]; then

echo "very good! ";

elif [[ $scores -gt 80 ]]; then

echo "good! ";

elif [[ $scores -gt 60 ]]; then

echo "pass! ";

else

echo "no pass! ";

fi;

The test is: [],[],

For,while,until:

for recycling method (for/do/done)

Syntax structure:

1. for... in statements

for variable in seq string

do

action

done

Description: seq string as long as the space character division, each time for... in read, will read the value in order, to the previous variable.

Example (testfor.sh):

#!/ bin/sh

for i in $(seq 10); do

echo $i;

done;

seq 10 produces 1 2 3... 10 spaces separate strings.

2.for((assignment; condition; operation statement))

for((assignment; condition; operation statement))

do

action

done;

Example (testfor2.sh):

#!/ bin/sh

for((i=1;i

Tags: Statements conditions instances loops selections variables characters structures results syntax runs usage strings methods spaces tests operations processes controls commands Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Huawei Docker Apple NVidia