shell编程
if条件语句实例
1. if 在使用新的关键词 (如 then else 等) 时,可以另起一行,也可以用 ';' 分割;但 必须以 fi 结尾。
$ a="Hello"
$ b="World"
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'"; fi
'Hello' is not the same as 'World'
$ if [ "$a" != "$b" ]
then
echo "'$a' is not the same as '$b'"
fi
'Hello' is not the same as 'World'
上面两种写法都可以,得到的结果一致。
要以fi结尾,成对出现
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'";
>
# 如果不以 fi 结尾, shell 将显示一个 > 符号,等待用户继续输入其它命令,如果这时,用户自己手动再输入 fi, 则结果将正常显示:
'Hello' is not the same as 'World'
2. test, [ 和 [[ 在进行字符串比较时,可以使用 =, !=, -z, -n 等形式 (比如上例中的 !=), 也可以使用 > 或者 < (但 test 和 [ 使用 < 或 > 时需要转义),但三者在进行整数比较时,必须使用 -eq, -ne, -gt, -lt 等形式
$ c=11
$ d=2
$ if [ "$c" \> "$d" ]; then echo "$c is greater than $d"; else echo "$c is less than $d"; fi
11 is less than 2
$ if [ "$c" -gt "$d" ]; then echo "$c is greater than $d"; else echo "$c is less than $d"; fi
11 is greater than 2
# 对于整数比较,我们需要使用 -gt 等表达式,如果使用 > 或
$ a="Ab"
$ b="a"
$ if [ "$a" > "$b" ]; then echo "This expression is wrong"; fi
This expression is wrong
$ if [ "$a" < "$b" ]; then echo "This expression is wrong"; fi
This expression is wrong
# 如果不进行转义,> 和 < 仅被理解为重定向符,条件判断结果始终为真。
$ if [ "$a" \< "$b" ]; then echo "'$a' is less than '$b'"; else echo "'$a' is greater than '$b'"; fi
'Ab' is less than 'a'
# 在字符串比较时,使用每个字母的ASCII数值来决定排序(小写字母大于大写字母),并从第一位开始比较。
$ if [[ "$a" < "$b" ]]; then echo "'$a' is less than '$b'"; else echo "'$a' is greater than '$b'"; fi
'Ab' is greater than 'a'
# [[ 在比较字符串时不需要转义,但是似乎对大小写字母的大小判断结果与 [ 不同,我暂时还没有查到原因,小伙伴们在使用时一定要注意。
3. test 和 [ 二者是一致的,即 'test expr' 与 [ expr ] 所起的作用完全相同。
$ a="Hello"
$ b="World"
$ if [ "$a" != "$b" ]; then echo "'$a' is not the same as '$b'"; fi
'Hello' not the same as 'World'
$ if test "$a" != "$b" ; then echo "'$a' is not the same as '$b'"; fi
'Hello' not the same as 'World'
4. [[ 是 test 和 [ 的加强版,支持 && 等形式逻辑判断,进行算数扩展和正则表达比较等。
$ a=1
$ b=2
$ if [ $a -gt 0 -a $b > 0 ]; then echo "Both a and b are greater than 0"; fi
Both a and b are greater than 0
$ if [ $a -gt 0 && $b > 0 ]; then echo "Both a and b are greater than 0"; fi
-bash: [: missing `]'
$ if [[ $a -gt 0 && $b > 0 ]]; then echo "Both a and b are greater than 0"; fi
Both a and b are greater than 0
# [ 仅支持 -a (逻辑与) 和 -o (逻辑或) 这样的逻辑操作符,而 [[ 支持 && 和 ||, 更灵活。
if [ "Hello World" =~ Hello ]; then echo "Example of regular expression comparison"; fi
-bash: [: =~: binary operator expected
if [[ "Hello World" =~ Hello ]]; then echo "Example of regular expression comparison"; fi
Example of regular expression comparison
# [[ 支持正则表达比较,而 [ 不支持。
[ 和 [[ 才是 条件判断命令,其后面跟着要判断的条件 (空格分割,很重要), ] 和 ]] 则表示条件判断的结束
$ a=1
$ b=2
$ if [ $a==$b ]; then echo "$a equals $b"; fi
1 equals 2
$ if [[ $a==$b ]]; then echo "$a equals $b"; fi
1 equals 2
# 如果不加空格,条件判断不能正常进行
$ if [[ $a == $b ]]; then echo "$a equals $b"; else echo "Now you konw the importance of using space"; fi
Now you konw the importance of using space