Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH Converting String to boolean variable

Tags:

bash

shell

What's the best way to convert a literal string (e.g. "True" into the appropriate bash boolean variable). For instance java has java.lang.Boolean.valueOf(String)

Right now I'm using this in Bash:

if [ "${answers[2]}" = "TRUE" ] ; then
    clean=true; 
else 
    clean=false; 
fi

is there a way to do it and avoid the IF statement?

edit: to clarify its not by choice that I have String variable containing "TRUE" instead of just using a boolean variable. for full context this is the code

ans=$(yad --title='YadExample' --form --field=Opt1:CHK FALSE  --field=Opt2:CHK FALSE --field=Opt3:CHK TRUE);
#at this point the "yad" program is returning a string seperated by '|', e.g "TRUE|FALSE|TRUE"
IFS="|"
set -- $ans
answers=( $@ )
unset IFS
if [ "${answers[0]}" = "TRUE" ] ; then clean=true; else clean=false; fi
if [ "${answers[1]}" = "TRUE" ] ; then var2=true; else var2=false; fi
if [ "${answers[2]}" = "TRUE" ] ; then var3=true; else var3=false; fi
like image 976
bluphoenix Avatar asked Aug 02 '26 15:08

bluphoenix


1 Answers

You could write a function to do the conversion for you:

function boolean() {
  case $1 in
    TRUE) echo true ;;
    FALSE) echo false ;;
    *) echo "Err: Unknown boolean value \"$1\"" 1>&2; exit 1 ;;
   esac
}

answers=(TRUE FALSE TRUE)
clean="$(boolean "${answers[0]}")"
var2="$(boolean "${answers[1]}")"
var3="$(boolean "${answers[2]}")"

echo $clean $var2 $var3

prints

true false true

Or, a little fancier:

function setBoolean() {
  local v
  if (( $# != 2 )); then
     echo "Err: setBoolean usage" 1>&2; exit 1 ;
  fi

  case "$2" in
    TRUE) v=true ;;
    FALSE) v=false ;;
    *) echo "Err: Unknown boolean value \"$2\"" 1>&2; exit 1 ;;
   esac

   eval $1=$v
}

answers=(TRUE FALSE TRUE)

setBoolean clean "${answers[0]}"
setBoolean var2 "${answers[1]}"
setBoolean var3 "${answers[2]}"

echo $clean $var2 $var3
like image 91
andrewdotn Avatar answered Aug 04 '26 05:08

andrewdotn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!