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
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
As per Jonathan's comment:
variable=$(( 1 == 1 ? 1 : 0 ))
I revised the original answer which just echo
'd the value of the condition operator, it didn't actually show any assignment.
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. ;]
another way
case "$variable" in
condition ) result=1;;
*) result=0;;
esac
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