带有if else语句和调试问题的简单bash脚本

时间:2011-10-30 05:11:27

标签: linux bash shell unix

我正在处理一个简单的bash脚本,无论用户输入什么choice,都会打印第一个条件的结果。有人能解释一下这里发生了什么吗?另外,如何调试这样的bash脚本?当我尝试使用shell脚本插件在ecplise中进行调试时,唯一的选择是“ant build”,当我尝试它时,它什么都不做!

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

3 个答案:

答案 0 :(得分:2)

[ $choice="Y" ]替换$choice,然后查看附加了'=“Y”'的替换是否为非空字符串。你的意思是[ "$choice" = Y ]

答案 1 :(得分:0)

如果认为你没有任何争论就启动了你的脚本。 在这种情况下,$ 1指的是什么,[ -f $1 ]总是如此。 尝试使用参数启动脚本以找出答案。

答案 2 :(得分:0)

为了跟踪脚本的执行情况,请使用

set -x

这将使shell在解释器看到它们时逐行打印出来的值......然而,在这种情况下,它并没有告诉你:

$ cat /tmp/test.sh 
set -x
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



$ bash /tmp/test.sh 
+ '[' -f ']'
+ echo 'Are you sure you want to delete ? Y for yes, N for no'
Are you sure you want to delete ? Y for yes, N for no
+ read choice
N
+ '[' N=Y ']'
+ echo okay
okay

嗯......实际上,它确实告诉你'[$ choice =“Y”]'不正确,但它没有告诉你为什么它是错的或如何解决它。