Getting Started with Shell Scripts_10

Shell flow control

Unlike Java, PHP and other languages, the flow control of sh cannot be empty, such as (the following is the writing method of PHP flow control):

<?php
if (isset($_GET["q"])) {
    search(q);
}
else {
    // 不做任何事情
}

You can't write this in sh/bash. If there is no statement execution in the else branch, don't write this else .

if else

if

The syntax of the if statement is:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

Written in one line (for terminal command prompt):

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

The fi at the end is the reverse spelling of if, and similar ones will be encountered later. 

if else

if else syntax format:

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if else-if else

if else-if else syntax format:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

The following cases determine whether two variables are equal:

a=10
b=20
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 "没有符合的条件"
fi

输出结果:a 小于 b

The if else statement is often used in conjunction with the test command as follows:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo '两个数字相等!'
else
    echo '两个数字不相等!'
fi

输出结果:两个数字相等!

for loop

Similar to other programming languages, Shell supports for loops .

The general format of a for loop is:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

写成一行: (注意此种写法,多了分号!!!)
for var in item1 item2 ... itemN; do command1; command2… done;

When the variable value is in the list, the for loop executes all commands once, using the variable name to get the current value in the list. Command can be any valid shell command and statement. The in list can contain substitutions, strings, and filenames.

The in list is optional, and without it, the for loop uses the command-line positional arguments .

For example, to sequentially output the numbers in the current list:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

输出结果:
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

Sequentially output characters in a string:

for str in 'This is a string'
do
    echo $str
done
输出结果:This is a string

while statement

A while loop is used to continuously execute a series of commands and also to read data from an input file; commands are usually test conditions . Its format is:

while condition
do
    command
done

行1,首先进行条件测试,如果传回值为0(条件测试为真),则进入循环,执行命令区域,否则

不进入循环,介绍while 命令

 行3,执行命令区域,这些命令中,应该要有改变条件测试的命令,这样,才有机会在

有限步骤后结束执行while循环(除非想要执行无穷循环)。

 行4,回到行1,执行while命令

The following is a basic while loop, the test condition is: if int is less than or equal to 5, then the condition returns true. int starts at 0 and increases by 1 each time the loop is processed. Running the above script returns the numbers 1 to 5, then terminates.

#!/bin/sh
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

运行脚本,输出:
1
2
3
4
5

In use, the Bash let command is used, which is used to execute one or more expressions. There is no need to add $ to indicate variables in variable calculation. For details, please refer to: Bash let command

while loop can be used to read keyboard information. In the following example, the input information is set to the variable FILM, and pressing <Ctrl-D> ends the loop.

echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的网站名: '
while read FILM
do
    echo "是的!$FILM 是一个好网站"
done

运行脚本,输出类似下面:
按下 <CTRL-D> 退出
输入你最喜欢的网站名:菜鸟教程
是的!菜鸟教程 是一个好网站

Infinite loop

Infinite loop syntax format:

while :
do
    command
done

or

while true
do
    command
done

or

for (( ; ; ))

until loop

The until loop executes a series of commands until the condition is true and stops. The until loop is just the opposite of the while loop.

The conditional test of the while loop is the true value, and the until loop is the false value.

While loops are generally preferred over until loops, there are times—and only rare cases—that until loops are more useful .

until syntax format:

until condition
do
    command
done

 行1,如果条件测试结果为假(传回值不为0),就进入循环。

 行3,执行命令区域。这些命令中,应该有改变条件测试的命令,这样子,才有机会在有限步骤后结束执行until 循环(除非你想要执行无穷循环)。

 行4,回到行1,执行until命令。

Condition can be any test condition, the test happens at the end of the loop, so the loop executes at least once - take care of this .

case

Shell case statements are multiple-choice statements. You can use the case statement to match a value with a pattern, and if the match succeeds, execute the matching command. The format of the case statement is as follows:

case 值 in
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac

The case works as shown above. The value must be followed by the word in, and each pattern must end with a closing parenthesis . The value can be a variable or a constant. After the matching finds that the value matches a certain pattern, all commands during the period are executed until ;; .

The value will detect every pattern that matches. Once the pattern is matched, no other patterns will be continued after the corresponding command of the matched pattern is executed . If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command .

The following script prompts for 1 to 4 to match each pattern:

echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac

Enter different content, there will be different results, for example:

输入 1 到 4 之间的数字:
你输入的数字为:
3
你选择了 3

out of the loop

In the loop process, sometimes it is necessary to force out of the loop when the loop end condition is not reached. Shell uses two commands to achieve this function: break and continue .

break command

The break command allows to break out of all loops (terminate execution of all subsequent loops) .

In the example below, the script goes into an infinite loop until the user enters a number greater than 5. To break out of this loop and return to the shell prompt, use the break command.

#!/bin/bash
while :
do
    echo -n "输入 1 到 5 之间的数字:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "你输入的数字为 $aNum!"
        ;;
        *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束"
            break
        ;;
    esac
done

执行以上代码,输出结果为:
输入 1 到 5 之间的数字:3
你输入的数字为 3!
输入 1 到 5 之间的数字:7
你输入的数字不是 1 到 5 之间的! 游戏结束

continue

The continue command is similar to the break command, except that it does not jump out of all loops, only the current loop .

Modify the above example:

#!/bin/bash
while :
do
    echo -n "输入 1 到 5 之间的数字: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "你输入的数字为 $aNum!"
        ;;
        *) echo "你输入的数字不是 1 到 5 之间的!"
            continue
            echo "游戏结束"
        ;;
    esac
done

Running the code shows that when a number greater than 5 is entered, the loop in this example does not end and the statement  echo "game over"  is never executed.

esac

The syntax of case is very different from the C family language, it requires an esac (that is, the case in reverse) as the end marker, each case branch is surrounded by a right parenthesis, and two semicolons are used to indicate break .

Remark:

The for loop in the shell can not only use the method described in the article.

It may be a bit awkward for friends who are used to for loops in other languages.

for((assignment;condition:next));do
    command_1;
    command_2;
    commond_..;
done;

As you can see above, the for loop here is similar to the one in C, but not exactly the same.

Under normal circumstances, the shell variable call needs to add $, but it is not required in the (()) of for . Let's look at an example:

#!/bin/bash
for((i=1;i<=5;i++));do
    echo "这是第 $i 次调用";
done;

执行结果:

这是第1次调用
这是第2次调用
这是第3次调用
这是第4次调用
这是第5次调用

Similar to C, assignment and next execution can be executed in the loop statement before the code. Note here: if you want to perform the next operation in for in the loop body, remember to add $ to the variable, otherwise the program will become Infinite loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482994&siteId=291194637