Monday, June 18, 2012

Bash ternary operation

Ternary operation allows to assign a variable one of two values depending on the evaluation of a Boolean condition. It's also known as conditional operator and inline if. In several programming languages it's expressed using the ?: operator:

assign_condition ? value_if_true : value_if_false

Bash ternary operation (works for numeric and string conditions)

[ condition ] && variable=value_if_true || variable=value_if_false
Example
b='aaa'; c='bbb'; d
[ b == 'zzz' ] && a=1 || a=0 # 0 is assigned to a

Bash ternary operation for numeric conditions only

(( assign_condition ? value_if_true : value_if_false ))
Example
b=3; c=10; d=7
(( a = b<5 ? c : d )) # 10 is assigned to a

References

Ternary operator in Bash (stackoverflow)
?: operator at Wikipedia
Ternary operator in bash

No comments:

Post a Comment