目錄
1、運算子
2、流程控制
2.1 If判斷
2.2 case陳述句
2.3 For回圈
2.4 while回圈
3、Read讀取控制臺輸入
1、運算子
- “$((運算式))”或“$[運算式]”
- expr + , - , \*, /, % (分別是加,減,乘,除,取余)
注意:expr運算子間要有空格
練習:
[root@localhost ~]# expr 2 + 3
5
[root@localhost ~]# expr `expr 2 + 3` \* 4 //利用expr計算(2+3)*4
20
[root@localhost ~]# S=$[(2+3)*4] //采用$[運算子]方式計算
[root@localhost ~]# echo $S
20
2、流程控制
2.1 If判斷
if [ 條件判斷式 ];then
程式
fi
或者
if [ 條件判斷式 ]
then
程式
fi
注意事項:
- [ 條件判斷式 ],中括號和條件判斷式之間必須有空格
- if后要有空格
練習:輸入一個數字,如果是1,則輸出banzhang zhen shuai,如果是2,則輸出cls zhen mei,如果是其它,什么也不輸出,
[root@localhost test]# vim if.sh
#!/bin/bash
if [ $1 -eq "1" ];then
echo banzhang zhen shuai
elif [ $1 -eq "2" ];then
echo cls zhen mei
fi
[root@localhost test]# bash if.sh 1
banzhang zhen shuai
[root@localhost test]# bash if.sh 2
cls zhen mei
[root@localhost test]# bash if.sh 3
2.2 case陳述句
case $變數名 in
"值1")
如果變數的值等于值1,則執行程式1
;;
"值2")
如果變數的值等于值2,則執行程式2
;;
…省略其他分支…
*)
如果變數的值都不是以上的值,則執行此程式
;;
esac
注意事項:
- case行尾必須為單詞“in”,每一個模式匹配必須以右括號“)”結束,
- 雙分號“;;”表示命令序列結束,相當于java中的break,
- 最后的“*)”表示默認模式,注意這里的*沒有雙引號,相當于java中的default,
練習:輸入一個數字,如果是1,則輸出banzhang,如果是2,則輸出cls,如果是其它,輸出renyao,
[root@localhost test]# vim case.sh
#!/bin/bash
case $1 in
1)
echo banzhang
;;
2)
echo cls
;;
*)
echo renyao
;;
esac
[root@localhost test]# bash case.sh 1
banzhang
[root@localhost test]# bash case.sh 2
cls
[root@localhost test]# bash case.sh 4
renyao
2.3 For回圈
語法1:
for (( 初始值;回圈控制條件;變數變化 ))
do
程式
done
練習:從1加到100
[root@localhost test]# vim for1.sh
#!/bin/bash
s=0
for (( i=1;i<=100;i++))
do
s=$[$s+$i]
done
echo $s
[root@localhost test]# bash for1.sh
5050
語法2:
for 變數 in 值1 值2 值3…
do
程式
done
注:這個語法就是將值1、值2、值3;分別賦給變數進行回圈,
練習:列印所有輸入引數,
[root@localhost test]# vim for2.sh
#!/bin/bash
for i in $*
do
echo $i
done
[root@localhost test]# bash for2.sh 1 2 3
1
2
3
比較$*和$@的區別
(1)$*和$@都表示傳遞給函式或腳本的所有引數,不被雙引號“”包含時,都以$1、$2 …$n的形式輸出所有引數,
[root@localhost test]# vim for2.sh
#!/bin/bash
for i in $*
do
echo $i
done
for j in $@
do
echo $j
done
[root@localhost test]# bash for2.sh 1 2 3
1
2
3
1
2
3
(2)當它們被雙引號“”包含時,“$*”會將所有的引數作為一個整體,以“$1、$2 …$n”的形式輸出所有引數;“$@”會將各個引數分開,以“$1” “$2”…”$n”的形式輸出所有引數,
[root@localhost test]# vim for2.sh
#!/bin/bash
for i in "$*"
do
echo $i
done
for j in "$@"
do
echo $j
done
[root@localhost test]# bash for2.sh 1 2 3
1 2 3
1
2
3
2.4 while回圈
while [ 條件判斷式 ]
do
程式
done
練習:從1加到100
[root@localhost test]# vim while.sh
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[$s+$i]
i=$[$i+1]
done
echo $s
[root@localhost test]# bash while.sh
5050
3、Read讀取控制臺輸入
Read(選項)(引數)
選項:
- -p:指定讀取值時的提示符;
- -t:指定讀取值時等待的時間(秒),
引數
- 變數:指定讀取值的變數名
練習:提示7秒內,讀取控制臺輸入的名稱,
[root@localhost test]# vim read.sh
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds" NAME
echo $NAME
[root@localhost test]# bash read.sh
Enter your name in 7 seconds yanshuai
yanshuai
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/240918.html
標籤:其他
