How do I set $? or the return code in Bash?

80,585

Solution 1

#!/bin/bash

RC=1

while [ $RC -eq 1 ]
do

  #do something until it returns 0    

  RC=$?
done

Solution 2

You can set an arbitrary exit code by executing exit with an argument in a subshell.

$ (exit 42); echo "$?"
42

So you could do:

(exit 1)    # or some other value > 0 or use false as others have suggested
while (($?))
do
    # do something until it returns 0    
done

Or you can emulate a do while loop:

while 
    # do some stuff
    # do some more stuff
    # do something until it returns 0    
do
    continue  # just let the body of the while be a no-op
done

Either of those guarantee that the loop is run at least one time which I believe is what your goal is.

For completeness, exit and return each accept an optional argument which is an integer (positive, negative or zero) which sets the return code as the remainder of the integer after division by 256. The current shell (or script or subshell*) is exited using exit and a function is exited using return.

Examples:

$ (exit -2); echo "$?"
254
$ foo () { return 2000; }; foo; echo $?
208

* This is true even for subshells which are created by pipes (except when both job control is disabled and lastpipe is enabled):

$ echo foo | while read -r s; do echo "$s"; exit 333; done; echo "$?"
77

Note that it's better to use break to leave loops, but its argument is for the number of levels of loops to break out of rather than a return code.

Job control is disabled using set +m, set +o monitor or shopt -u -o monitor. To enable lastpipe do shopt -s laspipe. If you do both of those, the exit in the preceding example will cause the while loop and the containing shell to both exit and the final echo there will not be performed.

Solution 3

false always returns an exit code of 1.

#!/bin/bash
false
while [ $? -eq 1 ]
do
#do something until it returns 0    
done

Solution 4

Some of answers rely on rewriting the code. In some cases it might be a foreign code that you have no control over.

Although for this specific question, it is enough to set $? to 1, but if you need to set $? to any value - the only helpful answer is the one from Dennis Williamson's.

A bit more efficient approach, which does not spawn a new child (but is a also less terse), is:

function false() { echo "$$"; return ${1:-1}; }
false 42

Note: echo part is there just to verify it runs in the current process.

Solution 5

I think you can do this implicitly by running a command that is guaranteed to fail, before entering the while loop.

The canonical such command is, of course, false.

Share:
80,585

Related videos on Youtube

JohnnyFromBF
Author by

JohnnyFromBF

Updated on July 09, 2022

Comments

  • JohnnyFromBF
    JohnnyFromBF almost 2 years

    I want to set a return value once so it goes into the while loop:

    #!/bin/bash
    while [ $? -eq 1 ]
    do
    #do something until it returns 0    
    done
    

    In order to get this working I need to set $? = 1 at the beginning, but that doesn't work.

  • Elliot Chance
    Elliot Chance almost 9 years
    Should be $(exit 42); echo "$?"
  • SourceSeeker
    SourceSeeker almost 9 years
    @ElliotChance: The dollar sign in my answer represents the prompt and works as-is. What you propose would also work, but isn't necessary.
  • boweeb
    boweeb about 6 years
    Note that you can use the range 0-255 but what actually happens is a modulo against 256. That means you can exit 300 and $? will be 44. Also, exit -1 would return 255 (a strange habit I've seen a lot). Just something to be aware of. It's best to just return the value you desire so stick to 0-255 so you (or someone else) won't get surprised.
  • Ar5hv1r
    Ar5hv1r over 5 years
    While I would avoid calling this function false (which could be confusing for readers), using a function is significantly faster than a subshell. A rough microbenchmark suggests more than 100x overhead with a subshell.
  • chukko
    chukko over 5 years
    why confusing? does the same as a traditional false command, just improved as it allows you to set your preferred error value/
  • Ar5hv1r
    Ar5hv1r over 5 years
    Because false 2 will have different behavior depending on whether or not your function is in the environment.
  • chukko
    chukko about 5 years
    all standard callers of false will still work (as false is only expected to return nonzero). the only really confusing part is calling it false 0 (which should maybe throw an error to avoid confusion). so it does not break anything - it will just provide additional value. if anybody is confused, they could easily use their own name (and break their scripts in case the function is not defined). i prefer overloading and backward compatibility to new name and breaking compatibility, but YMMV.
  • Ar5hv1r
    Ar5hv1r about 5 years
    But it's not backwards-compatible - the intent is to return a specific return code, which is not false's semantics. If you use false 42 in an environment that doesn't include this function you'll get subtly unexpected results (likely a 1 return code). If you use a different name you'll get a clear error message if your environment is not configured as intended.
  • chukko
    chukko about 5 years
    Sure but the point of backwards compatibility is the use case of the original command - i.e. return non-zero error code, which it does. This argument is an extension of that. You cannot expect exactly 1 - some unix flavors dont return 1. So the only unexpected case is false 0 - there i agree it should throw an error. Thats more of a philosophical topic of whether you like overloading or not. YMMV. If you dont, rename, if you do, dont. Pick your own poison. Neither is the golden bullet. We dont need to agree on that. Anybody reading this has enough background info to decide himself.
  • toolforger
    toolforger almost 5 years
    @boweeb -1 mod X == X-1 is pretty normal, you essentially continue the 0,1,...,X-1 sequence into negatives. See en.wikipedia.org/wiki/Modulo_operation for variations and rationale.
  • boweeb
    boweeb over 4 years
    @toolforger -- yup... that's what I said above. I'm not confused about the math. I'm confused why a developer would want to use a convoluted way to get to 255. My best guess is the convention implies the 255 return code isn't meant to be meaningful (and writing it as -1 is marginally easier to write(?)). RC 1 is common for a generic/unspecified error but I've never seen anything actually eval $? for 255 (specifically).