Bash – Return on error in shellscript instead of exit on error

bashfunctionshell

I know that set -e is my friend in order to exit on error. But what to do if the script is sourced, e.g. a function is executed from console? I don't want to get the console closed on error, I just want to stop the script and display the error-message.

Do I need to check the $? of each command by hand to make that possible ?

Here an example-script myScript.sh to show the problem:

#!/bin/sh
set -e

copySomeStuff()
{
    source="$1"
    dest="$2"
    cp -rt "$source" "$dest"
    return 0
}

installStuff()
{
    dest="$1"
    copySomeStuff dir1 "$dest"
    copySomeStuff dir2 "$dest"
    copySomeStuff nonExistingDirectory "$dest"
}

The script is used like that:

$ source myScript.sh
$ installStuff

This will just close down the console. The error displayed by cp is lost.

Best Answer

I would recommend having one script that you run as a sub-shell, possibly sourcing a file to read in function definitions. Let that script set the errexit shell option for itself.

When you use source from the command line, "the script" is effectively your interactive shell. Exiting means terminating the shell session. There are possibly ways around this, but the best option, if you wanted to set errexit for a session, would be to simply have:

#!/bin/bash

set -o errexit

source file_with_functions
do_things_using_functions

Additional benefit: Will not pollute the interactive session with functions.

Related Question