fasionchan

读万卷书,行万里路,品万味肴,撸万行码。

Shell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function if_continue() {
    if [ -z "$1"  ]; then
        local hint="continue(y/n)? "
    else
        local hint="$1, continue(y/n)? "
    fi

    while true; do
        read -p "$hint" yn
        [ "$yn" == "n"  ] && return 1
        [ "$yn" == "y"  ] && return 0
    done

}


function continue_or_exit() {
    local hint="$0"
    local code="$1"

    if [ -z "$code" ]; then
        local code='0'
    fi

    if_continue "$hint" || exit "$code"
}

循环

基本结构

1
2
3
4
5
6
7
8
while 条件
do
    循环体
done

while 条件; done
    循环体
done

方括号条件

1
2
3
while [ -z $name ]; do
    read -p 'Input name: ' name
done

命令条件

1
2
while read value; do
    echo "Input value: $value"

永久循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while true
do
    # do something
    sleep 1
done

while true; do
    # do something
    sleep 1
done

while :
do
    # do something
    sleep 1
done

输入重定向

1
2
3
while 条件; do
    循环体
done < input.txt

输出重定向

1
2
3
while 条件; do
    循环体
done > output.txt

捕获Ctrl-C

1
trap continue_or_exit 2

Comments