Shell – Unix command that immediately returns a particular return code

command lineexit-statusshell

Is there a standard Unix command that does something similar to my example below

$ <cmd here> 56
$ echo Return code was $?
Return code was 56
$

<cmd here> should be something that can be fork-execed and leaves 56 as the exit code when the process exits. The exit and return shell builtins are unsuitable for what I'm looking for because they affect the invoking shell itself by exiting out of it. <some cmd> should be something that I can execute in non-shell contexts – e.g., invoking from a Python script with subprocess.

E.g., /usr/bin/false always exits immediately with return code 1, but I'd like to control exactly what that return code is. I could achieve the same results by writing my own wrapper script

$ cat my-wrapper-script.sh # i.e., <some cmd> = ./my-wrapper-script.sh
#!/usr/bin/bash
exit $1
$ ./my-wrapper-script.sh 56
$ echo $?
56

but I'm hoping there happens to exist a standard Unix command that can do this for me.

Best Answer

  1. A return based function would work, and avoids the need to open and close another shell, (as per Tim Kennedy's comment):

    freturn() { return "$1" ; } 
    freturn 56 ; echo $?
    

    Output:

    56
    
  2. using exit in a subshell:

    (exit 56)
    

    With shells other than ksh93, that implies forking an extra process so is less efficient than the above.

  3. bash/zsh/ksh93 only trick:

    . <( echo return 56 )
    

    (that also implies an extra process (and IPC with a pipe)).

  4. zsh's lambda functions:

    (){return 56}