suncool 发表于 2018-8-27 06:54:10

shell脚本编程之基础篇(二)

# [ tom == Tom ]  
# echo $?
  
1
  
# [ tom == tom ]
  
# echo $?
  
0
  

  
# 变量替换要尽量用双引号,如果不用的话,如果变量不存在为空,会报错
  
# [ tom == $name ]
  
-bash: [: tom: 期待一元表达式
  
# [ tom == "$name" ]
  
# echo $?
  
1
  
# [[ tom == $name ]]
  
# echo $?
  
1
  

  
# name=xiu
  
# [ tom == $name ]
  
# echo $?
  
1
  
# [ tom == "$name" ]
  
# echo $?
  
1
  

  
# 要尽量使用 [[ ]]
  
# [ 'a' > 'b' ]
  
# echo $?
  
0
  
# [ 'a' < 'b' ]
  
# echo $?
  
0
  
# [[ 'a' > 'b' ]]
  
# echo $?
  
1
  
# [[ 'a' < 'b' ]]
  
# echo $?
  
0
  

  
# 在 [] 中变量替换一定要加双引号,但是在 [[ ]] 中可以不加
  
# [ -z $a ] && echo yes || echo no
  
yes
  
# [ -n $a ] && echo yes || echo no
  
yes
  
# [ -n "$a" ] && echo yes || echo no
  
no
  
# [ -z "$a" ] && echo yes || echo no
  
yes
  
# [[ -n $a ]] && echo yes || echo no
  
no
  
# [[ -z $a ]] && echo yes || echo no
  
yes
  
#============================================================================
  

  
# name=haha
  
# echo $name
  
haha
  
# [[ "$name" =~ ha ]]
  
# echo $?
  
0
  
# [[ "$name" =~ h ]]
  
# echo $?
  
0
  
# [[ "$name" =~ hx ]]
  
# echo $?
  
1
  
# [[ "$name" =~ xx ]]
  
# echo $?
  
1


页: [1]
查看完整版本: shell脚本编程之基础篇(二)