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?

3
  • y=$(case "$x" in true ) echo false ;; * ) echo "Unknown Value for x=$x" 1>&2 ; echo "nonesuch" ;; esac) ??
    – shellter
    Commented Dec 30, 2020 at 23:24
  • 2
    This question/answer is relevant: stackoverflow.com/questions/41204576/…
    – cam
    Commented Dec 30, 2020 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
    Commented Dec 30, 2020 at 23:29

1 Answer 1

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 :-)

3
  • 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.
    Commented Dec 30, 2020 at 23:40
  • @Ali No, it does not. Both true and false are regular strings. Commented Dec 31, 2020 at 4: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
    Commented Jan 2, 2021 at 17:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.