Fish shell: 翻转一个布尔值

Fish shell: flip a boolean value

我要疯了吗?我想翻转一个布尔变量。我想到了这个:

function toggle_light_colorscheme
  if eval $LIGHT_COLORSCHEME
    set -U LIGHT_COLORSCHEME false
  else
    set -U LIGHT_COLORSCHEME true
  end
end

鱼有布尔值吗?我怀疑不是。但是它有 falsetrue 命令,我可以 man 它们。无论如何,我可能不需要布尔值。我想要做的就是拥有一个全局变量,当设置时,这意味着我在 fish 和 vim 中使用浅色方案。如果未设置,我将使用深色的。必须有一种更简单的方法来做到这一点,我想要这样的东西:

set -U LIGHT_COLORSCHEME (not $LIGHT_COLORSCHEME)

Does fish even have booleans?

没有。事实上,它根本没有类型,就像它受到启发的 POSIX shell 一样。每个变量都是一个字符串列表。

But it has false and true commands

是的。这些命令 return 分别为 1 和 0。任何 return 状态 != 0 都被视为错误代码,因此为假,而 0 为真(在这方面它是 C 的倒数)。

All I want to do is to have a global variable which, when set, would mean that I'm using a light color scheme in fish and vim. If it's not set I'm using the dark one.

当然,这可以工作。有几种不同的方法可以解决这个问题。您可以使用变量 具有 一个元素这一事实来表示它是真的,或者您使用它是例如1.

前者的工作方式类似于

# Check if variable is "true" by checking if it has an element
if set -q LIGHT_COLORSCHEME[1]
# ...
# Flip the variable
set -q LIGHT_COLORSCHEME[1]; and set -e LIGHT_COLORSCHEME[1]; or set LIGHT_COLORSCHEME 1

(当然你也可以创建一个 "flip" 函数——不幸的是 "not" 是一个对命令 return 状态而不是变量值进行操作的关键字)

后者看起来像

if test "$LIGHT_COLORSCHEME" = 1 # the "=" here tests string-equality, but that shouldn't matter.
# ...
# Flip the variable
test "$LIGHT_COLORSCHEME" = 1; and set LIGHT_COLORSCHEME 0; or set LIGHT_COLORSCHEME 1

I came up with this:

function toggle_light_colorscheme if eval $LIGHT_COLORSCHEME

您误解了 eval 的作用。它 运行 的参数 为代码 。 IE。它将尝试将 LIGHT_COLORSCHEME 的值作为命令 执行。因此,如果您在 $PATH 中的某处有一个名为“1”的命令,它将 运行 that!

要测试条件,请使用 test

2.5 年后,我正在搜索 "flipping (pseudo-)boolean variable in fish" 并降落在这里! Whosebug 可能是所有(开发)人员中最大的书面历史……

顺便说一句。我借助内置数学函数轻松解决了这个问题!!

假设名为 bool 的变量已设置为 01(布尔值在任何低级语言中的实际解释方式):

set bool (math abs\((math $bool - 1)\))

_正确跳过括号实际上是主要挑战! fish 的仅带括号的 cmd 替换样式非常方便,但会干扰需要内部参数的函数 (),也许还有更好的方法……

我是 Fish 的新手,很快就遇到了这个问题。经过反复试验,我决定我最喜欢的解决方法是使用 set -qset -e。换句话说,true 表示变量已定义,否则为 false。所以你可以像这样用一个衬里捕获你的变量:

if test $status -eq 0; set isSuccessful 1; end

之后,您可以:

if set -q isSuccessful
  echo "Success!"
end

对于上面的示例,您可以将 LIGHT_COLORSCHEME 切换为:

if set -q LIGHT_COLORSCHEME
  set -e LIGHT_COLORSCHEME
else
  set LIGHT_COLORSCHEME 1
end