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
-
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 exitFrom carson -
You need a semicolon or a line break between
ifandthen, i.e.if $? -ne 0; then ... fior
if $? -ne 0 then ... fiFrom Dan Andreatta -
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)
From Marcel -
#!/bin/sh rm somefile if [ $? -ne 0 ] then echo 'error' fi exitFrom slubman -
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" fiYou can also negate the if by doing this:
if ! rm foo; then echo "It failed" fiMarcel : Or excluding if entirely: rm foo || echo 'It failed';James : And if you want to do more than one thing if it fails: rm foo || { echo 'It failed'; exit 1; }From Ernie
0 comments:
Post a Comment