My .bashrc file is modularized and I've got some error checking in it. In bash scripts, I typically have a function _errexit (or something similar) that I call when I detect an error and want to exit.

In the case of my bashrc file(s), I don't want to exit (it would close the shell) - but I do want to display an error message and stop processing immediately.

Any ideas how this might be possible?

2 Answers 2


In BASH you can use the return built-in:

return [n]

Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script.

For other shells it might work differently of course.

If you can possibly rewrite the main script as a loop, you could use the break statement based on the outcome of the loop command.


Check the result of your processing and continue only when nothing has failed.

if [ $? -ne 0 ]; then
   if [ $? -ne 0 ]; then
      echo OK

When you have a lot of modules, consider an extra shell variable.
EDIT: With the extra variable you can prevent deep-nesting (just repeat the if-block).

if [[ ${ERRORSFOUND} -eq 0 ]]; then
   if [[ $? -ne 0 ]]; then
  • OP is asking exactly about how not to continue - i.e. what exactly should display_error_function (in your parlance) look like as not to exit the shell completely. I take it he already has something along these lines in his script.
    – peterph
    Apr 30, 2014 at 14:43
  • @peterph: That "not to continue" part is handled in Walter A's answer by putting all the rest of the script in the else part. However if there are many modules, this might give an undesirably deep nesting.
    – celtschk
    Apr 30, 2014 at 15:01
  • @celtschk: The second code fragment (with an extra shell variable) was introduced to prevent deep nesting. You can repeat the if-test for a lot of module_x calls. When 1 call fails, you fall, all subsequent tests on ERRORSFOUND will fail.
    – Walter A
    Apr 30, 2014 at 15:57
  • @celtschk my point is, that it doesn't really stop processing the script, unless you do the nesting. And that will make the script cluttered. Unless you put it into a loop in which case one could use the break statement. However, a loop is not always the best form of putting such a script together.
    – peterph
    Apr 30, 2014 at 17:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .