if [ 條件 ] then 指令 fi 或 if [ 條件 ];then 指令 fi
提示:分號至關於命令換行,上面兩種語句等同。linux
特殊寫法if [ -f "$file1" ];then echo 1;figit
至關於 [ -f "$file1" ] && echo 1github
1)輸入2個數字,比較大小shell
#!/bin/bash #no1 if [ $# -ne 2 ] then echo "USAGE $0 num1 num2" exit 1 fi a=$1 b=$2 if [ $a -lt $b ];then echo "yes,$a less than $b" exit fi if [ $a -eq $b ];then echo "yes,$a equal $b" exit fi if [ $a -gt $b ];then echo "yes,$a greater than $b" exit fi
2)若是/server2/scripts下面有if3.sh就輸出if3.sh到屏幕,若是沒有自動建立bash
[root@chensiqi1 scripts]# cat chensiqi.sh #!/bin/bash path=/server2/scripts file=if3.sh if [ ! -d $path ] then mkdir -p $path echo "directory is not exsist!" fi if [ ! -f $path/$file ] then touch $path/$file echo "file is not exsist!" else echo "file is exsist!" fi
if [ 條件 ] then 指令 else 指令 fi
特殊寫法:if [ -f "$file1" ];then echo 1;else echo 0;filess
至關於[ -f "file1" ] && echo 1 ||echo 0code
1)若是/server2/scripts下面有if3.sh就輸出if3.sh到屏幕,若是沒有就自動建立server
[root@oldboy scripts]# cat chensiqi.sh #!/bin/bash file=/server2/scripts/if3.sh path=`dirname $file` if [ -f $file ];then cat $file exit 0 else if [ ! -d $path ];then mkdir -p $path echo "$path is not exist,already created it." echo "1234" >> $file fi if [! -f $file ];then echo "1234" >> $file echo "$file is not exist,already created it." fi fi
if [ 條件1 ];then 指令1 elif [ 條件2 ];then 指令2 elif [ 條件3 ];then 指令3 elif [ 條件4 ];then 指令4 else 指令n fi
1)判斷兩個整數大小ip
[root@oldboy scripts]# cat chensiqi.sh #!/bin/bash if [ $# -ne 2 ];then echo "USAGE $0 num1 num2" exit 1 else num1=`echo $1 | sed 's#[0-9]##g'` num2=`echo $2 | sed 's#[0-9]##g'` fi if [ ${#num1} -eq 0 -a ${#num2} -eq 0 ];then if [ $1 -lt $2 ];then echo "$1 less than $2!" exit elif [ $1 -eq $2 ];then echo "$1 equal $2!" exit else echo "$1 great than $2!" exit fi else echo "num1 num2 must be digit!" fi
一、if判斷的基本語法get