在Linux中,我们知道有几种方式可以运行.sh
脚本
- 通过
sh
或者bash
命令来运行 - 通过
source
来运行 - 通过
./xxx.sh
来运行(这种方式要求对脚本文件有r
和x
权限才行)
今天在写脚本的过程中,遇到了一个问题,关于[]
判断符,脚本如下:
#!/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
功能,当然其中没有包含[]
样式的测试。