I\'m looking a way to build conditional assignments in bash:
In Java it looks like this:
int variable= (condition) ? 1 : 0;
In addition to the other more general answers (particularly as per Jonathan's comment and Kevin's more general answer [which also supports strings]) I'd like to add the following two solutions:
0 or 1 based on the condition:(as the question's example suggests.)
The general form would read
(condition); variable=$?;
where $variable results in being either 0 or 1 and condition can be any valid conditional expression.
E.g. checking a variable ...
[[ $variableToCheck == "$othervariable, string or number to match" ]]
variable=$?
... or checking a file's existence ...
[ -f "$filepath" ]
fileExists=$?
... or checking the nummerical value of $myNumber:
(( myNumber >= 1000000000 ))
is_huge_number=$?
variable gets declared in any case, unlike in griffon's answer:[ -z "$variable" ] && variable="defaultValue"
Please note: In Bash, the special variable $? always contains the exit code of the previously executed statement (or statement block; see the man bash for more details). As such, a positive result is generally represented by the value 0, not 1 (See my comment below, thanks Assimilater for pointing it out). Thus, if the condition is true (e.g [[2 eq 2]]) then $?=0.
If instead you need 0 or 1 in your variable (e.g. to print or do mathematical calculations) then you need to employ boolean negation using a leading exclamation mark (as pointed out by GypsySpellweaver in the comments below): ( ! condition ); variable=$? or ! ( condition ); variable=$?. (However, readability in terms of what happens might be a bit less obvious.)
Another possible solution by Jonathan would be variable=$(( 1 == 1 ? 1 : 0 )) - which, however, is creating a subshell.
If you want to avoid the creation of a subshel, keep good readability or have arbitrary conditions, use one of the following solutions.
as it is done in most other answers, it could adapted as follows:
(condition) \
&& variable=true \
|| variable=false
e.g as in
[[ $variableToCheck == "$othervariable, string or number to match" ]] \
&& variable="$valueIfTrue" \
|| variable="$valueIfFalse"
or to get 1 in a positive check, and 0 upon failure (like in the question's example):
[[ $variableToCheck == "$othervariable, string or number to match" ]] \
&& variable=1 \
|| variable=0
(for the last example, - as already mentioned in the notes above - the same can be achieved with boolean negation using a leading exclamation mark:
[[ ! $variableToCheck == "$othervariable, string or number to match" ]]
variable=$?
myvar="default" && [[ ]] && myvar="non-default" , and$valueIfTrue is conditionally evaluated only if needed,variable=$((i++)), or{ variable=$1; shift; }variable=$(find / -type f -name ListOfFilesWithThisNameOnMySystem)variable gets declared in any case, unlike in griffon's answer:[ -z "$variable" ] && variable="defaultValue"