13

I would like to generate some exit code, say 20.
But if I do on shell:

$ exit 20

the shell is closed (X-Windows case) or I am logged out (text console case). Of course, inside .sh scripts, this command works fine.

I have tested with no success:

$ return 20
bash: return: can only `return' from a function or sourced script
$ break 20
bash: break: only meaningful in a `for', `while', or `until' loop

Is there any way to assign a value to $? variable?

3
  • Could you describe why you need this?
    – Kusalananda
    Commented Mar 8, 2018 at 6:46
  • @Kusalananda : I have developed a script that executes some command(s) from a config text file and reacts depending of its exit code and/or output data. Sometimes those command(s) return a useful and known exit code, and sometimes you need to forge this exit code as desired. I preferred not to enlarge the question, but i f you think more details could be useful to understand the problem to solve, I could edit the original question and add some example. Commented Mar 8, 2018 at 20:10
  • Thanks. I was wondering because it's an uncommon thing to do, and sometimes we get what we call "XY questions" where someone asks about "X" but it's really "Y" that they need help with and "X" might even be a convoluted unnecessary thing to do to solve "Y".
    – Kusalananda
    Commented Mar 8, 2018 at 21:02

1 Answer 1

15

Exit in a subshell:

(exit 20)

Or you can write a function:

ret () { return $1; }
ret 20
3
  • Working OK. Thanks you, Olorin. Someone expanding on why the ( ) trick works would be nice. Commented Mar 8, 2018 at 1:41
  • 2
    @SopalajodeArrierez: Because it's exiting from the subshell and not your current shell.
    – jesse_b
    Commented Mar 8, 2018 at 1:46
  • 2
    As mentioned, a subshell is created by the ( ... ). exit in the subshell only exist the subshell, not the original shell.
    – Olorin
    Commented Mar 8, 2018 at 1:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .