0

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

3 Answers 3

2

[ $choice="Y" ] Replaces $choice, then sees if the replacement with '="Y"' appended to it is a non-empty string. You meant [ "$choice" = Y ].

Sign up to request clarification or add additional context in comments.

4 Comments

That works for the conditional statement. However, Y is then assigned to the choice variable which is something I don't want. How do I avoid that?
@ignacio -- when I first read that, I was parsing that as "Replacing $choice with "Y"... which isn't possible because $choice is an rvalue. Reading it again, I see that you mean 'Replaces $choice with its value', and the value is interpreted as a variable which is assigned the value "Y". After all is said and done, $choice remains equal to 'N', and $N is equal to 'Y'.
It does not replace 'choice'. It tests whether the string "$choice=Y" is nonempty.
@IgnacioVazquez-Abrams: So what is another way to do what I want without using read. i.e. I want to compare the value of variable choice with the string "Y" but I don't want to change the value of choice.
0

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.

Comments

0

In order to track the execution of your script use

set -x

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:

$ 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

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.

1 Comment

As Ignacio told, when [ has only zero/one argument, it treats it as a string, which is true if it's not empty. So + '[' N=Y ']' is basically showing a test for the emptyness of the N=Y string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.