How to build a conditional assignment in bash?

后端 未结 8 2025
慢半拍i
慢半拍i 2021-01-31 01:04

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

In Java it looks like this:

int variable= (condition) ? 1 : 0;
8条回答
  •  盖世英雄少女心
    2021-01-31 01:58

    Big ups to @Demosthenex and especially @Dennis Williamson for the shortest and easiest solution I've seen. Leave it to bash to require a bunch of parentheses for a simple ternary assignment. Ahh, the 60s! And to put it all together in 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's see what happened!
    SCHOOL                       # unchanged! (it was already defined)
    

    I wrote that a long time ago.. these days I'd probably get more excited over a solution like...

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

    $OTHERSDKiphoneos

提交回复
热议问题