How to build conditional assignment in bash?

I am looking for a way to create conditional assignments in bash:

In Java, it looks like this:

int variable= (condition) ? 1 : 0; 
+41
bash
Mar 14 '10 at 2:13
source share
8 answers

According to Jonathan's comment:

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

EDIT:

I reviewed the original answer, which is simply echo - the value of the condition statement, in fact it did not show any purpose.

+41
Mar 14 '10 at 2:15
source share

If you want to define default values ​​in a shell script, use the following code:

 : ${VAR:="default"} 

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

This is because this is my most common use case for such logic .;]

+49
Mar 14 '10 at 2:35
source share
 myvar="default" && [[ <some_condition_is_true> ]] && myvar="non-default" 

real examples:

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

The condition may be "((...))":

 filepath=/proc/drbd && (( $# > 0 )) && filepath=$1 
+17
Mar 14 '10 at 5:15
source share

Big ups for @Demosthenex and especially @Dennis Williamson for the shortest and easiest solution I've seen. Leave it bash to require a bunch of parentheses for a simple three-digit assignment. Ah, the 60s! And put it all together as an example ...

 echo $BASHRULES; # not defined # no output : ${BASHRULES:="SCHOOL"} # assign the variable echo $BASHRULES # check it SCHOOL # correct answer : ${BASHRULES="FOREVER?"} # notice the slightly different syntax for the conditional assignment echo $BASHRULES # let see what happened! SCHOOL # unchanged! (it was already defined) 

I wrote that a long time ago ... these days I will probably be more excited about a solution like ...

 PLATFORM=iphonesimulator OTHERSDK=iphone && [[ $PLATFORM=~os ]] \ && OTHERSDK+=simulator \ || OTHERSDK+=os 

$OTHERSDK β‡₯ iphoneos

+6
Mar 03 '13 at 5:57
source share

I wanted to do conditional assignment with strings, and I ended up with:

 SOWHAT=$([ "$MYVALUE" = "value" ] && echo "YES" || echo "NO") 
+6
Jan 28 '16 at 15:11
source share

In addition to other more general answers (especially for Jonathan comment and Kevin a more general answer [which also supports strings]) I would like to add the following two solutions:


setting the variable to either 0 or 1 based on the condition:

(as the example question shows).

General form will read

 (condition); variable=$?; 

where $variable causes either 0 or 1 and condition can be any valid conditional expression .

eg. variable check ...

 [[ $variableToCheck == "$othervariable, string or number to match" ]] variable=$? 

... or checking file existence ...

 [ -f "$filepath" ] fileExists=$? 

... or to check the numeric value of $myNumber :

 (( myNumber >= 1000000000 )) is_huge_number=$? 


The advantages of this solution are that

  • it supports arbitrary conditional expressions , including strings
    (which are not supported in Jonathan arithmetic expressions
  • that variable declared anyway, unlike giffon answer :
    [ -z "$variable" ] && variable="defaultValue"
    What would be the question if you want nameref later (for example, from inside a function).


Note: In Bash, is the special variable $? always contains the exit code of a previously executed statement (or statement block, see man bash for more details). Thus, a positive result is usually represented by a value of 0 rather than 1 (see my comment below , thanks to Assimilater for pointing this out ).

Thus, if the condition is true (for example, [[2 eq 2]] ), then $?=0 . If instead you need 0 or 1 in your variable (for example, to print or perform mathematical calculations), then you need to use the solution Jonathan variable=$(( 1 == 1 ? 1 : 0 )) , or - if you want to avoid creating subshells or having arbitrary conditions is the next solution.


setting a variable to arbitrary values:

as is done in most other answers, it can be adapted as follows:

 (condition) \ && variable=true \ || variable=false 

for example, as in

 [[ $variableToCheck == "$othervariable, string or number to match" ]] \ && variable="$valueIfTrue" \ || variable="$valueIfFalse" 

or get 1 in a positive test and 0 if it fails (for example, in the example question):

 [[ $variableToCheck == "$othervariable, string or number to match" ]] \ && variable=1 \ || variable=0 


The advantages of this solution are that

  • it can be considered a little better read than Kevin answer
    myvar="default" && [[ <some_condition_is_true> ]] && myvar="non-default" and
  • $valueIfTrue conditionally evaluated only if necessary , which will make a difference if you do something
    • with side effect like
      • variable=$((i++)) , or
      • { variable=$1; shift; }
    • high computing for example
      • variable=$(find / -type f -name ListOfFilesWithThisNameOnMySystem)
  • slightly shorter than ghostdog74 answer (which, however, is great if you have several conditions!)
  • does not open subshell, as in Pierre answer
  • and as stated above:
    • it supports arbitrary conditional expressions , including strings
      (which are not supported in Jonathan arithmetic expressions
    • that variable declared anyway, unlike giffon answer :
      [ -z "$variable" ] && variable="defaultValue"
      What would be the question if you want nameref later (for example, from inside a function).
+6
Mar 09 '16 at 11:14
source share

If you want to assign a value, if only an empty variable, use this:

 [ -z "$variable" ] && variable="defaultValue" 

You can also set each other's conditions on []

+3
May 01 '14 at 9:18
source share

another way

 case "$variable" in condition ) result=1;; *) result=0;; esac 
+2
Mar 14 '10 at 4:28
source share



All Articles