tags:

views:

263

answers:

4

I'm looking a way to build conditional assignments in bash:

In Java it looks like this:

int variable= (condition) ? 1 : 0;

Thanks in advance

+2  A: 

As per Jonathan's comment:

variable=$(( 1 == 1 ? 1 : 0 ))  

EDIT:

I revised the original answer which just echo'd the value of the condition operator, it didn't actually show any assignment.

Anthony Forloney
Nit-pick: that isn't an assignment - it is just a conditional expression. However, `variable=$(( 1 == 1 ? 1 : 0 ))` works as long as there are no spaces around the first '=' sign; you can omit all the spaces after that and it also works - but think about readability.
Jonathan Leffler
You can have complete freedom of spacing (and drop the dollar sign) if you move the opening double parentheses all the way to the left. `(( variable = 1 == 1 ? 1 : 0 ))` or `(( variable = (1 == 1) ? 1 : 0 ))` But it could be argued that it's more readable as given in the answer.
Dennis Williamson
Also, it should be noted that this operator only works for arithmetic operations in Bash.
Dennis Williamson
+2  A: 

If you want a way to define defaults in a shell script, use code like this:

: ${VAR:="default"}

Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default.

This is related because this is my most common use case for that kind of logic. ;]

Demosthenex
This is a valuable technique, but the only condition supported with the ':=' notation is 'set to "default" if value is unset or empty'. The more general notation in the question is supported directly in bash.
Jonathan Leffler
I agree completely, I gave it a disclaimer for being slightly off topic.
Demosthenex
Omitting the colon before equal tests only for the variable to be unset and doesn't change it if it's null.
Dennis Williamson
A: 

another way

case "$variable" in
  condition ) result=1;;
  *) result=0;;
esac
ghostdog74
+2  A: 
myvar="default" && [[ <some_condition_is_true> ]]  && myvar="non-default"

real examples:

DELIM="" && [[ "$APP_ENV_RESOLVED" != "" ]] && DELIM=$INNER_DELIM

The condition can be "(( ... ))" as well:

filepath=/proc/drbd && (( $# > 0 )) && filepath=$1
Kevin Little