sh与bash执行语法严谨问题

在Linux中,我们知道有几种方式可以运行.sh脚本

  • 通过sh或者bash命令来运行
  • 通过source来运行
  • 通过./xxx.sh来运行(这种方式要求对脚本文件有rx权限才行)

今天在写脚本的过程中,遇到了一个问题,关于[]判断符,脚本如下:

#!/bin/bash
# Program
#       这个程序会判断用户输入的是否为Y或者N
# History
# 2018/10/03    DingNan first release
read -p "make your choice Y(y) or N(n): " flag
[ "$flag" == "Y" -o "$flag" == "y" ] && echo "OK, continue" && exit 0
[ "$flag" == "N" -o "$flag" == "n" ] && echo "Oh, interrupt" && exit 0
echo "I don't know what you choice is\n" && exit 0

环境为Debian。通过sh来运行脚本会得到错误的输出结果,类似这种

sh05.sh: 8: [: Y: unexpected operator
sh05.sh: 9: [: Y: unexpected operator

但其实脚本本身是没有任何问题的。怎么说呢,如果你通过bash来运行这个脚本,你会发现,可以得到正确的输出。
其原因如下:

bash语法是sh语法的超集 - 系统上的/bin/sh可执行文件可能只提供标准的sh功能,当然其中没有包含[]样式的测试。

posted @ 2018-10-03 17:07  dn96  阅读(466)  评论(0)    收藏  举报