Bash boolean expression and its value assignment

后端 未结 4 1746
囚心锁ツ
囚心锁ツ 2020-12-15 04:56

Is there a way to to evaluate a boolean expression and assign its value to a variable?

In most of the scripting languages there is way to evaluates e.g



        
相关标签:
4条回答
  • 2020-12-15 05:31

    Rather than using ... && BOOL=0 || BOOL=1 suggested in the currently-accepted answer, it's clearer to use true and false.

    And since this question is about bash specifically (not POSIX shell), it's also better to use [[ instead of [ (see e.g. 1 and 2), which allows using == instead of =.

    So if you had to use a one-liner for something like this in bash, the following would be better:

    [[ "$PROCEED" == "y" ]] && should_proceed=true || should_proceed=false

    Then you can use the derived variable ergonomically in boolean contexts...

    if $should_proceed; then
      echo "Proceeding..."
    fi
    

    ...including with the ! operator:

    if ! $should_proceed; then
      echo "Bye for now."
      exit 0
    fi
    
    0 讨论(0)
  • 2020-12-15 05:39

    I would suggest:

    [ "$PROCEED" = "y" ] || BOOL=1
    

    This has the advantage over checking $? that it works even when set -e is on. (See writing robust shell scripts.)

    0 讨论(0)
  • 2020-12-15 05:42

    Assignment:

    found=$((count > 0))
    
    0 讨论(0)
  • 2020-12-15 05:44

    You could do:

    [ "$PROCEED" = "y" ] ; BOOL=$?
    

    If you're working with set -e, you can use instead:

    [ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1
    

    BOOL set to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.

    This will not throw errors, and you're sure $BOOL will be either 0 or 1 afterwards, whatever it contained before.

    0 讨论(0)
提交回复
热议问题