Tuesday, November 16, 2021

[SOLVED] Bash Can the ternary operator be used to set values to multiple variables?

Issue

the (pseudo) code for what i want to do:

n=100
desired=""
for i in {1..10} ; do
    (( $(numeric_command_output) < n ?
        set n to the output and desired to $i :
        keep n and desired unchanged )) ; done

I know how to manipulate one variable based on the condition using ternary operator, but can this be done in bash?


Solution

Can the ternary operator be used to set values to multiple variables?

Yes.

but can this be done in bash?

Yes.

(( ( tmp=$(numeric_command_output) ) < n ? (n=tmp, desired=$i) : 0 ))

or

(( tmp=$(numeric_command_output, tmp < n ? (n=tmp, desired=$i) : 0 ))


Answered By - KamilCuk