views:

29

answers:

2

Hi,

I use a script that extends using the bash source feature;

#!/bin/bash

source someneatscriptthatendsprematurely.sh

I would like to be able to return from that script, without breaking the main script.

Using exit breaks the main script, return is only valid in functions and experimenting with $(exit 1) does not seem to work either.

So, is it possible to return in a sub-bash script without breaking the main bash?

Any help appreciated!

+2  A: 

You need the return statement:

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.

You can see this in action with the following two scripts:

script1.sh:
    . script2.sh
    echo hello again
script2.sh:
    echo hello
    return
    echo goodbye

When you run script1.sh, you see:

hello
hello again
paxdiablo
How could I have missed this? Thanks a lot for your reply.
codar
A: 

Is it important that you can change environment variables? Since otherwise you can just execute the script by executing it without source:

someneatscriptthatendsprematurely.sh
Bart Sas