流程控制
順序執行
選擇執行
循環執行
順序執行:
條件選擇:if語句
if語句為選擇執行
注意:if語句可嵌套
單分支
if 判斷條件:then 條件為真的分支代碼 fi
雙分支
if 判斷條件; then 條件為真的分支代碼 else 條件為假的分支代碼 fi多分支
if CONDITION1 ; then if-true elif CONDITION2 ; then if-ture elif CONDITION3 ; then if-ture ... else all-false fi
條件判斷:case語句
case 變量引用 in PAT1) 分支1 ;; PAT2) 分支2 ;; ... *) 默認分支 ;; esac
case 支持glob 風格的通配符:
*:任意長度任意字符
?:任意單個字符
[]:指定范圍內的任意單個字符
a|b:a或b
練習:
1 、寫一個腳本/root/bin/createuser.sh ,實現如下功能:使用一個用戶名做為參數,如果指定參數的用戶存在,就顯示其存在,否則添加之;顯示添加的用戶的id號等信息
#!/bin/bash #descriptio #version 0.1 #author gm #date 20160812 if `id $1 &> /dev/null`;then echo "$1 user is exist;" else useradd $1 echo "useradd $1." echo "$1 `id $1`" fi
[root@CentOS6 bin]# createuser.sh gao gao user is exist; [root@CentOS6 bin]# createuser.sh test useradd test. test uid=522(test) gid=522(test) groups=522(test)
2 、寫一個腳本/root/bin/yesorno.sh ,提示用戶輸入yes或no, 并判斷用戶輸入的是yes 還是no, 或是其它信息
#!/bin/bash #description #version 0.2 #author gm #date 20160812 read -p "please input yes or no: " string case $string in [yY]|[yY][eE][sS]) echo "user input is yes.";; [nN]|[nN][oO]) echo "user input is no";; *) echo "user input is other";; esac
[root@CentOS6 bin]# yesorno.sh please input yes or no: yse user input is other [root@CentOS6 bin]# yesorno.sh please input yes or no: yes user input is yes. [root@CentOS6 bin]# yesorno.sh please input yes or no: y user input is yes.
3 、寫一個腳本/root/bin/filetype.sh,判斷用戶輸入文件路徑,顯示其文件類型(普通,目錄,鏈接,其它文件類型)
#!/bin/bash #description #version 0.1 #author gm #date 20160812 read -p "please file path: " path if [ ! -e $path ] ;then echo "$path is not exist." elif [ -h $path ] ;then echo "$path is link file." elif [ -f $path ] ;then echo "$path is common file." elif [ -d $path ] ;then echo "$path is dir file" else echo "$path is other file." fi
[root@CentOS6 bin]# filetype.sh please file path: /etc /etc is dir file [root@CentOS6 bin]# filetype.sh please file path: /dev/sda /dev/sda is other file. [root@CentOS6 bin]# filetype.sh please file path: /etc/fstab /etc/fstab is common file.
4 、寫一個腳本/root/bin/checkint.sh, 判斷用戶輸入的參數是否為正整數
#!/bin/bash #description #version 0.2 #author gm #date 20160812 read -p "please ont number of int: " num testnum=$num echo $num | grep -qE "^[0-9]+$" if [ $? -eq 0 ] ; then if [ $num -ne 0 ] ; then echo "$num is positive integer." else echo "$num in not positive integer." fi else echo "$num is not positive integer." fi
[root@CentOS6 bin]# checkint.sh please ont number of int: 123 123 is positive integer. [root@CentOS6 bin]# checkint.sh please ont number of int: sdfj sdfj is not positive integer. [root@CentOS6 bin]# checkint.sh please ont number of int: 1.123324 1.123324 is not positive integer. [root@CentOS6 bin]# checkint.sh please ont number of int: -123.123 -123.123 is not positive integer.
原創文章,作者:megedugao,如若轉載,請注明出處:http://www.www58058.com/36886