Lolly
Lolly

Reputation: 36402

shell script error status and syntax checking

I have written a shell script and I am using few commands like rm, ls, etc. In case where those commands fails , I am checking the return status '$?' . But If the script has some syntax error, how can I get the error status of it ? Basically I am going to source this script from another script using the 'source' command. So if the script which is sourced has any syntax error I want to display that in console. Is there any way to get that status ? In shell I executed the script with syntax error and I got the error like 'missing [' , but when I executed echo $? its returning 0 as the status, is this the behavior ? How can I get the status if the script has some syntax error or not ?

Upvotes: 2

Views: 1909

Answers (1)

Jens
Jens

Reputation: 72639

You can check the syntax of a shell script using the -n option prior to sourcing:

bash -n somescript  # Works also for sh, ksh, zsh et al.

will tell you if somescript is syntactically okay without actually running it. In a program:

if bash -n somescript; then
   . somescript
else
   printf '%s\n' "Uh-oh, somescript is not syntactically correct." >&2
fi

Upvotes: 2

Related Questions