BASH 将字符串转换为布尔变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14700579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH Converting String to boolean variable
提问by bluphoenix
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)
将文字字符串(例如“True”转换为适当的 bash 布尔变量)的最佳方法是什么?例如 java 有 java.lang.Boolean.valueOf(String)
Right now I'm using this in Bash:
现在我在 Bash 中使用它:
if [ "${answers[2]}" = "TRUE" ] ; then
clean=true;
else
clean=false;
fi
is there a way to do it and avoid the IF statement?
有没有办法做到这一点并避免 IF 语句?
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
编辑:为了澄清它不是我选择的,我有包含“TRUE”的字符串变量,而不仅仅是使用布尔变量。对于完整的上下文,这是代码
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
采纳答案by andrewdotn
You could write a function to do the conversion for you:
您可以编写一个函数来为您进行转换:
function boolean() {
case in
TRUE) echo true ;;
FALSE) echo false ;;
*) echo "Err: Unknown boolean value \"\"" 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 "" in
TRUE) v=true ;;
FALSE) v=false ;;
*) echo "Err: Unknown boolean value \"\"" 1>&2; exit 1 ;;
esac
eval =$v
}
answers=(TRUE FALSE TRUE)
setBoolean clean "${answers[0]}"
setBoolean var2 "${answers[1]}"
setBoolean var3 "${answers[2]}"
echo $clean $var2 $var3
回答by paxdiablo
You can just use something like:
你可以使用类似的东西:
[ "${answers[2]}" != "TRUE" ] ; clean=$?
You need to reverse the sense of the comparison if you want cleanset to 1 on the condition being true.
如果您想clean在条件为真时设置为 1,则需要反转比较的意义。
Your sequence then becomes:
然后您的序列变为:
[ "${answers[0]}" != "TRUE" ] ; clean=$?
[ "${answers[1]}" != "TRUE" ] ; var2=$?
[ "${answers[2]}" != "TRUE" ] ; var3=$?

