0

I am trying to remove something based on user input using bash/sh, here is my code :

echo "remove ? [Y/n]"
read REMOVE
if [ $REMOVE != "n" ] || [ $REMOVE !="N" ];then
  # ... do something ...
  echo "done"
fi

the error I am getting is something like:

./run.sh: line 8: syntax error near unexpected symbol « then »

./run.sh: line 8: `if [ $REMOVE != "n" ] || [ $REMOVE !="N" ];then'

I tried to add/remove spaces many times, and I still don't understand what happens. I also don't really understand all the differences between [[ statement ]] [statement] or ((statement)). If someone can help...

2
  • Related: stackoverflow.com/questions/19691082/… Commented May 23, 2015 at 12:24
  • @fvu $SHELL is zsh but the script is actually running in bash Commented May 23, 2015 at 12:31

3 Answers 3

2

In your original problem, you need a space here

$REMOVE != "N"

In your comment response to shruti1810, it sounds like your $REMOVE variable doesn't contain what you think it contains.

Try adding

echo $REMOVE

to your script.

I typically use this construct

if [ "x$REMOVE" != "xn" ] || [ "x$REMOVE" != "xN" ]
then
  # ... do something ...
  echo "done"
fi

to ensure that my arguments are both valid.

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

Comments

1

Please try this:

echo "remove ? [Y/n]"
read REMOVE
if [ $REMOVE != "n" ] && [ $REMOVE != "N" ]
then
  # ... do something ...
  echo "done"
fi

4 Comments

./run.sh: line 8 : [: n : expected unary operator (maybe it's not the english output, I translated it myself)
As far as the logic which you are trying to achieve, I feel you should be using && and not ||
Better yet: if [ x"$REMOVE" != xn -a x"$REMOVE" != xN ]; then ....
The x is not needed as long as you quote the $ variable -- although the answer is accepted it is erroneous and a timebomb waiting to blow
1

Quote the "$REMOVE" and insert space around the "!=" -- like this;

if [ "$REMOVE" != "n" ] || [ "$REMOVE" != "N" ];then
  # ... do something ...
  echo "done"
fi

The problem is that is REMOVE is not set or if it is set to an empty string (like if you just press return on the 'read') you will get $REMOVE substituted to nothing and your expression would look like [ != "N" ] which will produce an unary operator expected error.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.