带有 if else 语句的简单 bash 脚本以及调试问题
我正在编写一个简单的 bash 脚本,无论用户输入什么作为 choice
,第一个条件的结果始终会被打印。有人能解释一下这是怎么回事吗?顺便说一句,如何调试这样的 bash 脚本?当我尝试使用 shell 脚本插件在 ecplise 中进行调试时,唯一的选择是“ant build”,当我尝试它时,它什么也不做 arrgggh!
if [ -f $1 ]
then
echo "Are you sure you want to delete $1? Y for yes, N for no"
read choice
if [ $choice="Y" ]
then
echo "okay"
else
echo "file was not deleted"
fi
fi
I'm working on a simple bash script and no matter what the user inputs as choice
, the result of the first condition is always printed. Can someone explain what's going on here? On side note, how do you go about debugging a bash script like this? When I try debugging in ecplise using the shell script plugin, the only option is an "ant build" which, when I try it, does nothing arrgggh!
if [ -f $1 ]
then
echo "Are you sure you want to delete $1? Y for yes, N for no"
read choice
if [ $choice="Y" ]
then
echo "okay"
else
echo "file was not deleted"
fi
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[ $choice="Y" ]
替换$choice
,然后查看附加 '="Y"' 的替换是否为非空字符串。您的意思是[ "$choice" = Y ]
。[ $choice="Y" ]
Replaces$choice
, then sees if the replacement with '="Y"' appended to it is a non-empty string. You meant[ "$choice" = Y ]
.如果您认为您启动脚本时没有任何参数。
在这种情况下,$1 不代表任何内容,并且
[ -f $1 ]
始终为 true。尝试使用要弄清楚的参数来启动脚本。
If think you launch your script without any argument.
In that case $1 refers to nothing and
[ -f $1 ]
is always true.Try to launch your script with an argument to figure out.
为了跟踪脚本的执行,使用
这将使 shell 逐行打印出解释器看到的值...但是,在这种情况下,它不会告诉您太多信息:
嗯...实际上,它从字面上告诉您 '[ $choice="Y" ]' 是不正确的,但它并没有告诉您为什么它是错误的或如何修复它。
In order to track the execution of your script use
This will make the shell print out the values as the interpreter sees them, line by line... however, in this case, it doesn't tell you very much:
Well... actually, it literally tells you that '[ $choice="Y" ]' is incorrect, but it doesn't tell you why it's wrong or how to fix it.