Bash 字符串运算符

2023-01-03 08:57 更新

同其他编程语言一样,在 Bash 中,字符串也是一种数据类型。只要以" "引起来,不论是数字还是字符,都会被 Bash 视为字符串。如"Welcome to W3Cschool"

字符串运算符

1.= 等于运算符,等于时返回true

语法示例:

  1. Str1 = Str2

应用示例:

  1. #!/bin/bash
  2. Str1="W3Cschool.cn"
  3. Str2="W3C"
  4. if [ $Str1 = $Str2 ];
  5. then
  6. echo "True"
  7. else
  8. echo "False"
  9. fi

执行后得到以下结果:

  1. False

2.!= 不等于运算符,不等于时返回true

语法示例:

  1. Str1 != Str2

应用示例:

  1. #!/bin/bash
  2. Str1="W3Cschool.cn"
  3. Str2="W3C"
  4. if [[ $Str1 != $Str2 ]];
  5. then
  6. echo "True"
  7. else
  8. echo "False"
  9. fi

执行后得到以下结果:

  1. True

3.检查字符串长度是否为零。

  • -n,不为零时返回true

语法示例:

  1. -n Str

应用示例:

  1. #!/bin/sh
  2. Str="Welcome to W3Cschool"
  3. if [ -n $Str ];
  4. then
  5. echo "True"
  6. else
  7. echo "False"
  8. fi

执行后返回以下结果:

  1. True

4.检查字符串长度是否为空。

  • [-z string ]:如果string不为空(长度大于0),则判断为真。

应用示例:

  1. #!/bin/sh
  2. ANSWER=maybe
  3. if [ -z "$ANSWER" ]; then
  4. echo "There is no answer." >&2
  5. exit 1
  6. fi
  7. if [ "$ANSWER" = "yes" ]; then
  8. echo "The answer is YES."
  9. elif [ "$ANSWER" = "no" ]; then
  10. echo "The answer is NO."
  11. elif [ "$ANSWER" = "maybe" ]; then
  12. echo "The answer is MAYBE."
  13. else
  14. echo "The answer is UNKNOWN."
  15. fi

执行后返回以下结果:

  1. maybe

上面代码中,首先确定$ANSWER字符串是否为空。如果为空,就终止脚本,并把退出状态设为1。注意,这里的echo命令把错误信息There is no answer.重定向到标准错误,这是处理错误信息的常用方法。如果$ANSWER字符串不为空,就判断它的值是否等于yesno或者maybe

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号