0

I have created a very simple script (see below) but cannot get it to run properly. I always get messages saying

line 5: syntax error near unexpected token 'fi'
line 5: 'fi'

when I try to execute this script.

#!/bin/sh
rm /opt/file_name
if $? -ne 0 then
    echo 'error'
fi
exit

I am running this on Red Hat Linux if that makes any difference.

If any one can help identify what is wrong with the if statement I'd really appreciate it.

Bill

5 Answers5

5

You are missing a semicolon (and I'm not sure if it works without square brackets).

Alternatives:

if [[ $? -ne 0 ]];then

or

if ! test $? = 0; then

or

if [ $? -ne 0 ];then

or

test $? = 0 || echo 'error';

or even better:

rm /bla/bla || echo 'error';

(the last one is your whole script)

2

Here's a very handy alternative. The "test" command is itself a command like "rm". It sends a return code to "if": 0 if it succeeds and 1 or greater if it fails. So instead of checking the return code in the special $? variable, you can just do this:

if rm foo; then
    echo "It worked"
else
    echo "It failed"
fi

You can also negate the if by doing this:

if ! rm foo; then
     echo "It failed"
fi
Ernie
  • 5,324
  • 6
  • 30
  • 37
0

You need a semicolon at the end of that if statement as well as brackets:

#!/bin/sh

rm /opt/file_name

if [ $? -ne 0 ]; then

     echo 'error'

fi

exit
carson
  • 1,620
  • 11
  • 15
0

You need a semicolon or a line break between if and then, i.e.

if $? -ne 0; then
...
fi

or

if $? -ne 0
then
...
fi
Dan Andreatta
  • 5,384
  • 2
  • 23
  • 14
0
#!/bin/sh

rm somefile

if [ $? -ne 0 ]
then
     echo 'error'
fi

exit
slubman
  • 2,247
  • 16
  • 11