shell編程基礎二

一、流程式控制制

while循環:只要條件滿足一直循環

read -p "請輸入一個數字:" white_data
while  [ ${white_data} -lt 20 ]
do
    echo ${white_data}
    white_data=$((white_data + 1))
done

until循環:只要條件不滿足一直循環

until [ ${white_data} -qt 20 ]
do
    echo ${white_data}
done

case:類似於Java中的switch case

case $2 in
    +)
         echo "$1 + $3 = $(($1 + $3))"
            ;;
    -)
         echo "$1 - $3 = $(($1 - $3))"
            ;;
    \*)
         echo "$1 * $3 = $(($1 * $3))"
            ;;
    /)
         echo "$1 / $3 = $(($1 / $3))"
            ;;
    *)
    # 如果都不滿足 執行*)下的語句
        echo "$2 not "
esac

case 後面為值, in後面 )前面為判斷條件,如果符合會執行下面得命令,上方腳本實現的是基本的算術運算,當所有條件不滿足時執行 *)下的命令。

二、獲取命令行參數

echo "第一個參數為$1"
echo "第二個參數為$2"
echo "shell腳本名為 $0"
echo "shell腳本的參數個數為 $#"
echo "shell腳本的所有參數為 $*"

三、定義函數

方法1:

function hello()
{
    echo "hello"
}
hello

hello為方法名,在{}中寫命令,使用hello調用函數

方法2:

greet()
{
    echo "greet, ${LOGNAME}, today is $(date)"
}
greet

greet為方法名

帶參數的方法:

# 帶參數的方法
read -p "請輸入姓名: " name
# 與input相同功能
read -p "請輸入年齡: " age
function info
{
    echo -e "姓名為$1,\n 年齡為$2"
}
info
或者 info zhangsan 20 在調用方法時傳參