68

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.

12 Answers 12

169

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.

5
  • Should be $(exit 42); echo "$?" Commented Jul 14, 2015 at 4:35
  • 3
    @ElliotChance: The dollar sign in my answer represents the prompt and works as-is. What you propose would also work, but isn't necessary. Commented Jul 14, 2015 at 4:40
  • 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.
    – boweeb
    Commented Mar 21, 2018 at 14:00
  • @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.
    – toolforger
    Commented Jul 3, 2019 at 5:30
  • @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).
    – boweeb
    Commented Jan 29, 2020 at 13:33
30

false always returns an exit code of 1.

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

RC=1

while [ $RC -eq 1 ]
do

  #do something until it returns 0    

  RC=$?
done
9

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.

6
  • 1
    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.
    – dimo414
    Commented Dec 6, 2018 at 7:16
  • why confusing? does the same as a traditional false command, just improved as it allows you to set your preferred error value/
    – chukko
    Commented Dec 7, 2018 at 8:28
  • Because false 2 will have different behavior depending on whether or not your function is in the environment.
    – dimo414
    Commented Dec 8, 2018 at 1:01
  • 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.
    – chukko
    Commented Feb 18, 2019 at 18:15
  • 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.
    – dimo414
    Commented Feb 18, 2019 at 21:52
7

Didn't find anything lighter than just a simple function:

function set_return() { return ${1:-0}; }

All other solutions like (...) or [...] or false might contain an external process call.

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.

0
4

Old question, but there's a much better answer:

#!/bin/bash
until
    #do something until it returns success
do
    :;
done

If you're looping until something is successful, then just do that something in the until section. You can put exactly the same code in the until section you were thinking you had to put in the do/done section. You aren't forced to write the code in the do/done section and then transfer its results back to the while or until.

3

$? is a byte value in the range 0 to 255. Any numbers returned beyond this range will be remapped within it, akin to applying a bitwise AND operation with 255.

exit value - a rather forceful solution as it leads to the termination of a process or script.

return value - a typical solution.

Here are examples of exit:

# Create a subshell, but, exit it with an error code:
$( exit 0 ); echo $? # outputs: 0
$( exit 34 ); echo $? # outputs: 34
$( exit 1000 ); echo $? # outputs: 232
$( exit -1 ); echo $? # outputs: 255 

Here are examples of return:

# Define a `return_val` function and call it:
return_val() { return $1; }
return_val 0; echo $? # outputs: 0
return_val 34; echo $? # outputs: 34
return_val 1000; echo $? # outputs: 232
return_val -1; echo $? # outputs: 255
1

Would something like this be what your looking for ?

#!/bin/bash
TEMPVAR=1
while [ $TEMPVAR -eq 1 ]
do
  #do something until it returns 0
  #construct the logic which will cause TEMPVAR to be set 0 then check for it in the 
  #if statement 

  if [ yourcodehere ]; then
     $TEMPVAR=0
  fi
done
0

You can use until to handle cases where #do something until it returns 0 returns something other than 1 or 0:

#!/bin/bash

false
until [ $? -eq 0 ]
do
#do something until it returns 0    
done
0

This is what I'm using

allow_return_code() {
  local LAST_RETURN_CODE=$?
  if [[ $LAST_RETURN_CODE -eq $1 ]]; then
    return 0
  else
    return $LAST_RETURN_CODE
  fi
}

# it converts 2 to 0, 
my-command-returns-2 || allow_return_code 2
echo $?
# 0

# and it preserves the return code other than 2
my-command-returns-8 || allow_return_code 2
echo $?
# 8
0

Here is an example using both "until" and the ":"

until curl -k "sftp://$Server:$Port/$Folder" --user "$usr:$pwd" -T "$filename";
do :; 

done

Not the answer you're looking for? Browse other questions tagged or ask your own question.