3

Is it possible to exit a script from a function that is called using command substitution?

e.g

#/bin/bash
function do_and_check()
{
    ls $1 || exit
}

p=$(do_and_check /etc/passwd)
q=$(do_and_check /xxx)

the result of running this is

bash -x yyy                                                                                                             
++ do_and_check /etc/passwd                                                                                                                  
++ ls /etc/passwd                                                                                                                             
+ p=/etc/passwd
++ do_and_check /xxx
++ ls /xxx
ls: cannot access /xxx: No such file or directory
++ exit
+ q=
+ echo /etc/passwd
/etc/passwd

I would have liked the exit to take me out of the script, not out of the command substitution. Is that possible?

1 Answer 1

3

This:

p=$(do_and_check /etc/passwd)

is executing a subshell, and that's what you're exiting from. I would set the exit value in your function (to a non-zero value), and then check the return value $? after the command substitution.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Or, use set -e to have the script exit on any non-zero return status.
adding a $? check after each call to the function is what I want to avoid in the first place. set -e is too encompassing. I can call directly e.g. do_and_check xxx and have it set a known variable ala perl's $_; or pehraps do_and_check could kill its parent?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.