How to build a conditional assignment in bash?

后端 未结 8 2023
慢半拍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

    0 讨论(0)
  • 2021-01-31 01:59

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

    SOWHAT=$([ "$MYVALUE" = "value" ] && echo "YES" || echo "NO")
    
    0 讨论(0)
提交回复
热议问题