bash之条件判断(选择执行) 单分支if语句: if CONDITION; then if-true-分支 fi 示例:写一个脚本,如果文件不存在,就创建文件 #!/bin/bash # file=/root/fstab if [ ! -f $file ]; then touch $file fi 双分支if语句: if CONDITION; then if-true-分支 else if-true-分支 fi 示例:写一个脚本,如果文件不存在,就说文件不存在,并创建文件 #!/bin/bash # file=/root/fstab if [ -f $file ]; then echo "file is not exists.." else touch $file echo "touch file $file finished" fi 多分支if语句 if CONDITION1; then if- CONDITION1-true-分支 elif CONDITION2; then if- CONDITION2-true-分支 else 其他-分支 fi 示例:写一个脚本,传递一个参数,判断给定的参数类型 #!/bin/bash # if [ $# -lt 1 ]; then echo "Plz enter a file path." exit 1 fi if [ -f $1 ]; then echo "$1 is a file." elif [ -d $1 ]; then echo "$1 is a mulu" elif [ -b $1 ]; then echo "$1 is a kuai." else echo "unknow file type" fi case语句: 简洁版多分支if语句; 使用场景:判断某变量的值是否为多种情形中的一种时使用; 语法: case$VARIABLE in PATTERN1) 分支1 ;; PATTERN2) 分支2 ;; PATTERN3) 分支3 ;; ... *) 分支n ;; Esac 示例:判断用户给的参数,是数值,字符或者是其他类型 #!/bin/bash # read -p "Plz enter a shuzhi"char case $char in [a-z]) echo "A character" ;; [0-9]) echo "A digit" ;; *) echo "A unknown character" esac 示例:根据用户给定的选项,做相应的操作 #!/bin/bash # prog=$(basename $0) localfile="/var/tmp/$prog" #echo $localfile if [ $# -lt 1 ]; then echo "Usage: $prog start|stop|restart|status" exit 1 fi case $1 in start) if [ -f $localfile ]; then echo "$prog is starting yet" else touch $localfile && echo "starting $prog ok" || echo "starting $prog failed.." fi ;; stop) if [ -f $localfile ]; then rm -rf $localfile && echo "$prog is stoped..." else echo "$prog stopeding.." fi ;; restart) if [ -f $localfile ]; then rm -rf $localfile && touch $localfile && echo "restarting $prog ok..." else touch $localfile && echo "$prog is stoped,starting $prog ok..." fi ;; status) if [ -f $localfile ]; then echo "$prog is running..." else echo "$prog is stoping..." fi ;; *) echo "Usage: $prog start|stop|restart|status" exit esac
原文地址:http://zhangnan30.blog.51cto.com/2051991/1696322