If [$? -ne 0], then a syntax error, then unexpected

I am trying to execute the following UNIX shell script that does not work. I run it KornShell (ksh).

echo $?; if [ $? -ne 0 ] then failed $LINENO-2 $5 $6 fi failed() { echo "$0 failed at line number $1"; echo "moving $2 to failed folder" } 

This gives an error saying Syntax error:then unexpected. . Basically, I have to check the last executed ksh script return code with the highest / last statement, and if it is not equal to zero, I should call the function with an error with the given parameters. I tried to put a semicolon before this, but that didn't work either.

Can you help?

Edit1: Based on the inputs, I changed the code. However, the same problem exists.

 ksh ../prescript/Pre_process $1 $2 $3 rc=$?; if [[ $rc -ne 0 ]];then echo "failed"; exit 1; 

Edit2: It works for the part using square brackets. I feel like I used the bash script code for ksh. I ran into a problem while calling a function. Please let me know the appropriate way to call a function in ksh for this example.

+4
source share
3 answers

It looks like bash, not ksh

 failed() { echo "$0 failed at line number $1"; echo "moving $2 to failed folder" } if [[ $? -ne 0 ]] then failed $LINENO-2 $5 $6 fi 
+3
source

You need to be careful. First operation on $? usually clears it, so your if will not work.

You would be better off using:

 rc=$? echo $rc if [ $rc -ne 0 ] : 

Other than that, it works great for me:

 $ grep 1 /dev/null $ if [ $? -ne 0 ] > then > echo xx > fi xx $ grep 1 /dev/null $ echo $?; 1 $ if [ $? -ne 0 ] > then > echo yy > fi $ _ 

Note the lack of output in the latter. This is because echo pulled in the return value and overwritten it (because the echo was successful).

As an aside, you should tell us which UNIX and which ksh you are using. My working version is ksh93 under Ubuntu. Your mileage may vary if you use a smaller version.


It looks like from your update, your only problem now is the function call. This is most likely because you define it after using it. script:

 grep 1 /dev/null rc=$? if [ $rc -ne 0 ] then failed $rc fi failed() { echo Return code was $1 } 

gives:

 qq.ksh[6]: failed: not found 

a

 failed() { echo Return code was $1 } grep 1 /dev/null rc=$? if [ $rc -ne 0 ] then failed $rc fi 

produces

 Return code was 1 
+5
source

you are missing semicolons at the end of lines:

 if [ $? -ne 0]; then # … 
0
source

All Articles