1

Is there some way to assign one value out of some possible values in shell like this :

variable = $(command1) or $(command2)

Knowing that only one of these two commands gives a result

2 Answers 2

2

The || operator will evaluate command2 if command1 returns a non-zero (error) return code.

variable=$(command1 || command2)

Similarly, the && operator will evaluate command2 if command1 returns a (ok) zero return code.

variable=$(command1 && command2)

e.g. Assignment of variable:

var=$(ls zasdasd || echo "file does not exist") 
echo $var    ## outputs "file does not exist"

Error output can be suppressed by directing error stream 2 to /dev/null

var=$(ls zasdasd || echo "file does not exist") 2>/dev/null
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

variable=$(command1 2>/dev/null || command2 2>/dev/null)

This will assign output of command1 to variable if it is successful otherwise it will assign output from command2.

2>/dev/null is there to suppress stderr in case any of the commands fail.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.