Reputation:
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
Upvotes: 0
Views: 1558
Reputation: 4416
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.
Upvotes: 0
Reputation: 3742
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.
Upvotes: 0
Reputation: 798556
[ $choice="Y" ]
Replaces $choice
, then sees if the replacement with '="Y"' appended to it is a non-empty string. You meant [ "$choice" = Y ]
.
Upvotes: 2