1

In a Bash script, I'd like to define a boolean variable y to store the negated value of another boolean variable x. The following script,

#!/bin/bash

x=true
y=$(( ! "${x}" ))
echo "${y}"

sets variable y to 1. How can I change y so it evaluates to false instead?

Ali D.
  • 11
  • 1
  • 3
  • `y=$(case "$x" in true ) echo false ;; * ) echo "Unknown Value for x=$x" 1>&2 ; echo "nonesuch" ;; esac)` ?? – shellter Dec 30 '20 at 23:24
  • 2
    This question/answer is relevant: https://stackoverflow.com/questions/41204576/exclamation-mark-to-test-variable-is-true-or-not-in-bash-shell/41205067#41205067 – cam Dec 30 '20 at 23:25
  • You do understand what `true ; echo $?` means? If you want to use return values `0` and `not 0`, you'll need to translate from the number to the text that you want. Good luck. – shellter Dec 30 '20 at 23:29

1 Answers1

4

Bash does not have the concept of boolean values for variables. The values of its variables are always strings. They can be handled as numbers in some contexts but that's all it can do.

You can use 1 and 0 instead or you can compare them (with = or ==) as strings with true and false and pretend they are boolean. The code will be more readable but they are still strings :-)

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Hmm, I'm a bit confused, because `x=abc` (without quotes) is not allowed but `x=true` is. Does Bash internally convert "boolean" values to their string representation always before storing them? – Ali D. Dec 30 '20 at 23:40
  • @Ali No, it does not. Both `true` and `false` are regular strings. – oguz ismail Dec 31 '20 at 04:17
  • .What do you mean` x=abc` is not allowed? In bash and every shell I know about, such an assignment is the most basic of operations. `x=abc; echo $x` should produce `abc`, and `echo $?` returns `0`, indicating that that command executed successfully. What where you looking for? I'm only guessing here, but don't try to implement syntax you found handy in another language in your shell code. It will confuse future maintainers, etc. Good luck. – shellter Jan 02 '21 at 17:30