[dywang@dywmac zzz]$ cat sh03.sh #!/bin/bash read -p "請輸入一串數字: " -t 5 num num=$(echo "$num" | sed 's/ /+/g') total=$(echo "$num" | bc) echo $num=$total exit 0
[dywang@dywmac zzz]$ sh sh03.sh 請輸入一串數字: 12 34 2 4 12+34+2+4=52 [dywang@dywmac zzz]$ sh sh03.sh 請輸入一串數字: 1 3 5 7 1+3+5+7=16
[dywang@dywmac zzz]$ sh sh03.sh 請輸入一串數字: =
{num:-expr}
,當 num 沒設定或空字串時,num 變數就設成 expr,以避免使用者沒輸入的狀況。
[dywang@dywmac zzz]$ cat sh03.sh #!/bin/bash read -p "請輸入一串數字: " -t 5 num num=${num:-"1 2 3 4 5 6 7 8 9"} num=$(echo "$num" | sed 's/ /+/g') total=$(echo "$num" | bc) echo $num=$total exit 0
[dywang@dywmac zzz]$ sh sh03.sh 請輸入一串數字: 1+2+3+4+5+6+7+8+9=45