Return on error in shellscript instead of exit on error

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.


If you source that, it will ignore the #! and will apply set -e to the calling shell, so will apply to all subsequent commands.

you could force a sub-shell:

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

Also for safety:

  • Do not use all caps variable name, as likely to collide with environment names. (we had a question last week about why a script did not work, it had a variable PATH)

  • Use quotes.

  • Always use -t or -T option for cp, mv, ln. e.g.

    • cp -t destination_directory source_files …
    • cp -T source_file destination_file

    note that -t and -T are Gnu extensions, and not available on some other Unixes, so for portability you can in place of the -t option do:

    • cp source_files … destination_directory/

    I do not know of an alternate safe form for -T