bash if语句,切换

时间:2016-12-09 02:27:58

标签: bash shell terminal

这不起作用,每次都执行else子句:

state=false
function toggle {
  if [ ! $state ]
  then
    echo first
    state=true
  else
    echo second
    state=false
  fi
}

我希望多次调用toggle会在“第一”和“第二”之间交替输出,但我只会得到“第二”

4 个答案:

答案 0 :(得分:3)

test没有使用字符串truefalse作为布尔值。 test将任何非空字符串视为true,将空字符串视为false。

您需要执行显式比较:

state=false
function toggle {
  if [ "$state" = false ]
  then
    echo first
    state=true
  else
    echo second
    state=false
  fi
}

答案 1 :(得分:1)

在您的情况下,truefalse都只是字符串,其值为逻辑真值。

因此,无论状态是否包含单词truefalse[ ! $state ]将始终恢复为逻辑false - 触发您的else子句。

由于您已经在使用truefalse,因此您可以执行以下操作:truefalse都是有效的shell命令,除了返回错误之外什么都不做代码分别为0和1。由于if基本上评估命令(查找它,[是可执行文件)并使用它们的错误代码,你可以这样做:

if $state; 

$state可以是falsetrue,然后由if执行,并根据错误代码选择哪个特定代码块<{1}}块将被执行。

答案 2 :(得分:0)

我不知道它去了哪里,但我最喜欢的答案似乎已经消失了。

state=
function toggle {
  if [ ! $state ]
  then
    echo first
    state=true
  else
    echo second
    state=
  fi
}

答案 3 :(得分:0)

BASH 4+版本具有功能:

# -- Toggle between TRUE and FALSE with a variable every time called --
# Globals: None
# Arguments: boolean (pass in previous)
# Returns: boolean (switched value)
# --
toggle_true_false() {
    toggle="${1}"
    if [[ -z ${toggle} ]] || [[ ${toggle} = false ]] ; then
        toggle=true
    else
        toggle=false
    fi
    echo ${toggle}
}

如何使用它:

local toggle
while [[ 1 ]] ; do
    toggle=$(toggle_true_false ${toggle})
    if ${toggle} ;then echo "value is TRUE" ;else echo "value is FALSE" ;fi
done

基本上,我们声明一个变量,然后调用将反转其值并将其存储回该变量的函数。然后,您可以基于此切换值的值调用其他命令。

输出:

value is TRUE
value is FALSE
value is TRUE
value is FALSE
value is TRUE
value is FALSE
value is TRUE
....

进一步阅读:处理布尔值:How to declare and use boolean variables in shell script?以及如何使用函数:Passing parameters to a Bash function

相关问题