0

It is annoying to me that return 0 only works when a file is sourced and when doing a sub-shell you need to exit 0. I'm trying to create a function whose code will be evaluated in the parent scope so that it can do:

return 0 2>/dev/null exit 0 

This is the simplest solution in the parent's scope because if return fails then exit will work & it covers all cases. But it only works of course when coded in the parent scope because a return inside a function scope will obviously return from just the function.

How is it possible to do this? I prefer simplicity, but it may not be possible for this problem

1 Answer 1

3

One solution is this. Say we want to bail out of a script with exit code 42, whether it is sourced or whether it is run in its own process:

return 42 || exit 42 

I.e. try return 42. If that fails, try exit 42, which is not expected to fail.

3
  • I suppose it is not possible to combine these commands into say a function or inheritable alias? I'm guessing it is not, so I'm likely to accept your answer I'm just curious. Commented Jul 10, 2023 at 16:07
  • 1
    Aliases are not inherited via the environment. They can be defined in a .rc file, but that's more for personal customization. If I had to write a complex shell application consisting of multiple scripts where I wanted some common aliases, I'd have an environment variable called foobar_common (where foobar is the name of my application). This would hold the absolute path name of a file to be sourced, containing common definitions that are not inheritable. The top-level script would pass that to other scripts, which would source it using . "$foobar_common". Commented Jul 10, 2023 at 17:05
  • Alright, thanks for you help! Commented Jul 10, 2023 at 18:11

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.