Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

5 Answers 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)

share|improve this answer
    
Thanks. Working now. –  Bill Sherwin Mar 24 '10 at 15:39

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
share|improve this answer
    
Or excluding if entirely: rm foo || echo 'It failed'; –  Jimmy Mar 24 '10 at 16:08
    
And if you want to do more than one thing if it fails: rm foo || { echo 'It failed'; exit 1; } –  James Mar 24 '10 at 16:22

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
share|improve this answer
    
Thanks. working now. Bill –  Bill Sherwin Mar 24 '10 at 15:40

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
share|improve this answer
    
Thanks. working now. Bill –  Bill Sherwin Mar 24 '10 at 15:39
#!/bin/sh

rm somefile

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

exit
share|improve this answer
    
Thanks everyone, square brackets and a line break work. Bill –  Bill Sherwin Mar 24 '10 at 15:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.