
一、条件测试与比较1、test 测试表达式 常用test -f file echo true||echo false2、[ 测试表达式 ] 特别常用[ -f file ] echo true||echo false3、[[ 测试表达式 ]]二、流程控制1、流控制语句 if实例1#!/bin/bash#获取uid0(root)中的0idid | awk -F ‘[(]’ {printKaTeX parse error: Expected EOF, got } at position 2: 2}̲ echo your us…idif [KaTeX parse error: Expected EOF, got # at position 65: …fi 实例2判断登录的用户 #̲!/bin/bash ##是添加到shell 参数个数if [ $# -eq 1 ] #或 [[KaTeX parse error: Expected EOF, got # at position 1: #̲1 ]] 或 ((#1))thenif who|grep $1 /dev/nullthenecho $1 is active.elseecho $1 is not active.fielseecho Usage: $0 exit 1fi~执行后的结果[rootlocalhost shell]# sh if-if.sh rootroot is active.[rootlocalhost shell]# sh if-if.sh zabbixzabbix is not active.[rootlocalhost shell]# sh if-if.shUsage: if-if.sh[rootlocalhost shell]#实例3 if-elif…else-fi#!/bin/bash##if-elif…else-firead -p “how lod are you? age#使用shell算数运算符(())进行条件测试if ((age0||age120));then #[[ age 0 || age 120 ]]echo “out of range ”exit 1fiif ((age0age13));thenecho “child”elif ((age13age20));thenecho “callan!”elif ((age20age30));thenecho “P iii”elif ((age30age40));thenecho “P IV I”elseecho “Sorry I asked.”fi实例4#!/bin/bash##if 语句可以嵌套使用file$1[ $# -ne 1 ] echo “Usage: $0 exit 1#错误的写法 [ $# -ne 1 ] echo “Usage: $0 ; exit 1 这样”;” 不管前面的判断是否正确都会执行if [ -dfile]thenechoquot;file ] then echo quot;file]thenechofile is a directory”elif [ -f $file ]thenif [ -r $file -a -w $file -a -x $file ];thenecho “you have (rwx) permissioon onfile.quot;elseechoquot;file.quot; else echo quot;file.elseechofile is file.”fielseecho “$fles is neither a file nor a directory.”fi执行结果[rootlocalhost shell]# vim if-elif-if-else.sh[rootlocalhost shell]# sh if-elif-if-else.sh liuyou have (rwx) permissioon on liu.[rootlocalhost shell]# sh if-elif-if-else.sh liubliub is a directory[rootlocalhost shell]# touch qq[rootlocalhost shell]# sh if-elif-if-else.sh qqqq is file.[rootlocalhost shell]#深圳网站建设www.sz886.com