You can add an extra exit command after the return statement/command so that it works for both, executing the script from the command line and sourcing from the terminal.
Example exit code in the script:
if [ $# -lt 2 ]; then
echo "Needs at least two arguments"
return 1 2>/dev/null
exit 1
fi
The line with the exit
command will not be called when you source the script after the return
command.
When you execute the script, return
command gives an error. So, we suppress the error message by forwarding it to /dev/null
.