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.
cp
error and exiting with 1 exit code.set -e
sets theerrexit
option in the shell. When calling the function, thecp
fails and the shell exits for me.#!
and will applyset -e
to the calling shell, so will apply to all subsequent commands.()
when calling shell functions.${dest}
and${source}
are still unquoted, and they contain user input. I'm being a bit picky with you here, but you need to quote them in your script on your machine, or simple things like copying files with spaces in their names won't work. Sorry. I'm just trying to give constructive feedback.