Shell编程(五)脚本语法

${}: 数据“内容”删除,替换;{}: 列表

1. 条件测试: test

=~:正则匹配

2. if/then/elif/else/fi

#!/bin/bash

echo "Is it ok? yes or no"

read YES_OR_NO

if [ "$YES_OR_NO" = "yes" ]; then
    echo "is ok"
elif [ "$YES_OR_NO" = "no" ]; then
    echo "is not ok"
else
    echo "sorry"
    exit 1
fi

3. case/esac

#!/bin/bash
                       
echo "is it morning"   

read YES_OR_NO         

case "$YES_OR_NO" in   
yes|y|Yes|YES)         
    echo "good morning"
    echo "good morning"
    echo "good morning"
    echo "good morning"
    echo "good morning";;            
[nN]*)
    echo "good afternoon";; 
*)
    echo "sorry"       
    exit 1;;           
esac

4. for/do/done

#!/bin/bash

for Fruit in apple banana pear;do
    echo "I like $Fruit"
done

#!/bin/bash

for read_parm in $@;do
    echo $read_parm
done

5. while/do/done

#!/bin/bash

echo "Enter passward: "
read key
while [ "$key" != "douzi" ];do
    echo "Sorry, try again"
    read key
done

#!/bin/bash

Counter=1
while [ "$Counter" -lt 10 ];do
    echo "Here we go again"
    Counter=$(($Counter+1))
done

  • 采用 i++
#!/bin/bash

ip=115.239.210.27

i=1
while [ $i -le 5 ] 
do
    ping -c1 $ip &>/dev/null
    if [ $? -eq 0  ];then
        echo "$ip is up.."
    fi  
    let i++ 

done

6. break和continue

#!/bin/bash

cnt=0
while [ $cnt -lt $# ];do
    if [ $cnt -eq 2 ];then
        echo "this is break"
        break
    fi
    cnt=$(($cnt+1))
done

7. tee

功能:tee命令把结果输出标准输出,另一个副本输出到相应文件

原文地址:https://www.cnblogs.com/douzujun/p/10363633.html