1

I have a bash code in which I have made a function which is called in the program. I forgot to put a quotation mark in one of the statement because of which the script threw a syntax error.Following is the code :

#function
write_errors()
{
    #writes RIGHT TRUNCATION errors in bcp import
    temp_file=$1
    error_file=$2
    stepName=$3
    error_count=`fgrep -c "right truncation" ${error_file} "` #here is the extra quotation mark
    ...
}

#start of script
date
...
write_errors  #syntax error happens here
...
date #these lines are executed
rm -f ${temp}
rm -f ${error_file}
...
#end of script

My question is after the syntax error in write_errors, why does bash executes the line after the syntax error happened ? Why doesn't it quit at the syntax error like other languages?

1 Answer 1

2

By default, bash doesn't exit on error.

You can request that behaviour by adding the following line at the beginning of your script:

set -o errexit

Note that there's a shorthand for it:

set -e

This article has a few pointers as to why this isn't the default behaviour in bash.


If you want to write robust bash scripts, you might also want to look at another flag, nounset, which errors out on undefined variables.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the quick response, but why is it made by default ? What is the need of such a behavior where the program doesn't quit on syntax error ?
@snyder This page should have some details: mywiki.wooledge.org/BashFAQ/105 There are caveats to having set -e by default, because bash treats all errors (syntax errors, nonzero output codes) equivalently.
Great, that is what I was looking for :). Can you add this link in your answer.

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.