天天看點

shell程式設計中變量的應用:for,while,case,expect,if語句

一.for語句

1.for 語句的結構

for 
do
done
           

2.for語句的循環設定

`for NUM in    == for NUM in {..} == for NUM in seq  
           

in與seq的差別在seq更進階,可以設定步長,如seq 1 2 5(設定1-5之間的步長為

舉例:編寫一個腳本,後邊跟上使用者名檔案和密碼檔案,建立使用者!

#!/bin/bash
MAX_LINE=`wc -l $1 | cut -d " " -f `
for LINE_NUM in `seq  $MAX_LINE`
do
        USERNAME=`sed -n "${LINE_NUM}p" $1`
        PASSWORD=`sed -n "${LINE_NUM}p" $2`
        useradd $USERNAME
        echo $PASSWORD | passwd --stdin $USERNAME
done
           

二.while 語句

while 條件
do
done
           

三.if語句

if     條件
then   語句
elif   條件
then   語句
...
else   剩餘條件
fi
           

四.case語句

case
 word1 )
  action1
  ;;
 word2)
  action2
  ;;
 *)
  action_last
esac
           

五.expect

expect 是自動應答指令用于互動式指令的自動執行 spawn 是expect中的監控程式,其運作後會監控指令提出的互動問題

send 發送問題答案給互動指令

exp_continue 表示當問題不存在時繼續回答下面的問題

expecte of 表示問題回答完畢退出expect環境

interact 表示問題回答完畢留在互動界面

set NAME [ lindex $argvn ] 定義變量

expect示例1.:

vim ask.sh
    #!/bin/bash
    read -p "what's your name: " NAME
    read -p "How old are you: " AGE
    read -p "Which class you study: " CLASS
    read -p "You feel happy or terrible ?" FEEL
    echo $NAME is $AGE\'s old and $NAME is feel $FEEL
chmod +x ask.sh
vim ans.sh
    #!/bin/bash
    expect <<EOF
    spawn ask.sh     問題所在的腳本
    expect {
    name  { send "jay\r" ; exp_continue}  exp_continue 表示當問題不存在時繼續回答下面的問題
    old   {send "18\r" ; exp_continue}
    study { send "music\r" ; exp_continue }
        feel  { send "happy\r"}
    }
    expect eof               expect eof   表示問題回答完畢退出expect環境
    EOF
sh ans.sh