kit*_*ang 173 linux bash shell
我的代码:
#!/bin/sh
#filename:choose.sh
read choose
[ "$choose" == "y" -o "$choose" == "Y" ] && echo "Yes" && exit 0
[ "$choose" == "n" -o "$choose" == "N" ] && echo "No" && exit 0
echo "Wrong Input" && exit 0
Run Code Online (Sandbox Code Playgroud)
但是当我执行时
sh ./choose.sh
Run Code Online (Sandbox Code Playgroud)
终端提示我
[: 4: n: :Unexpected operator
[: 5: n: :Unexpected operator
Run Code Online (Sandbox Code Playgroud)
我的bash脚本有什么错误吗?谢谢!
Wol*_*lph 297
你的bash脚本没有错误.但是你用sh执行它,它的语法不太广泛;)
所以,bash ./choose.sh
改为运行:)
Nie*_*jou 280
POSIX sh不了解==
字符串相等性,因为这是一种bash -ism.请=
改用.
其他人说sh不支持括号是错误的,顺便说一句.
To execute it with Bash, use #!/bin/bash and chmod it to be executable, then use
./choose.sh
Run Code Online (Sandbox Code Playgroud)
你必须使用bash代替或使用标准sh重写你的脚本
sh -c 'test "$choose" = "y" -o "$choose" = "Y"'
Run Code Online (Sandbox Code Playgroud)
In fact the "[" square opening bracket is just an internal shell alias for the test command.
So you can say:
test -f "/bin/bash" && echo "This system has a bash shell"
Run Code Online (Sandbox Code Playgroud)
or
[ -f "/bin/bash" ] && echo "This system has a bash shell"
Run Code Online (Sandbox Code Playgroud)
... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.
你可以使用case/esac而不是if/else
case "$choose" in
[yY]) echo "Yes" && exit;;
[nN]) echo "No" && exit;;
* ) echo "wrong input" && exit;;
esac
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
169012 次 |
最近记录: |