2

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 ?

4
  • source executes the commands of another script in the context of the current shell, so you get statuses of commands. If you want to see the sh/bash exit status, use sh script; echo $? Commented Oct 9, 2012 at 9:14
  • Oops, it does not solve the problem, the subsequent commands are still executed Commented Oct 9, 2012 at 9:18
  • So, basically you need permanent error checking like ret=$?; [ $ret -eq 0 ] || exit $ret Commented Oct 9, 2012 at 9:19
  • You can run your shell with #!/bin/bash -e. It will then stop on error. Commented Oct 9, 2012 at 9:44

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.