1

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

some_command_to_run
VAR_TO_SET=$?

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

4

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
   ...
fi

You can actually just test a command directory like:

if ! mkdir foo; then
   ...
fi

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

  • 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
5

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
  • Yeah, I second the "why"... there might be a reasonable question here :) – medina Aug 2 '10 at 3:55
4

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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