Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there any easier/more elegant way to assign a return value to a variable? So far I've been doing something like:


But I would much prefer to have it all on one line and preferably without using the $? variable. Does anyone know how?

share|improve this question
up vote 4 down vote accepted

That is all I know as well. However, if you are just doing this repeatily to see if I command was sucessful with something like:

if [[ $? -ne 0 ]]; then

You can actually just test a command directory like:

if ! mkdir foo; then

You might have already know that, but figured it might help you :-)

share|improve this answer
In fact, if you're doing this repeatedly, you're probably looking for set -e, which tells the shell to stop processing the script immediately if a command returns nonzero. If one particular command may legitimately fail, a common idiom is command_that_may_fail || true. – Gilles Aug 2 '10 at 18:35

The question I have is "Why?". It's the facility provided by Bash to accomplish that function.

However, you can do this (in addition to what Kyle and Gilles showed):

do_something && do_on_success || do_on_failure
share|improve this answer
Yeah, I second the "why"... there might be a reasonable question here :) – medina Aug 2 '10 at 3:55

That's all there is. If you really want it on one line, you can write some_command_to_run; VAR_TO_SET=$?. You could make it a two-liner function, but I don't recommend it because it will make your scripts less readable (one more thing to learn to be able to understand your code).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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