gpt4 book ai didi

fish shell : flip a boolean value

转载 作者:行者123 更新时间:2023-12-02 08:10:23 27 4
gpt4 key购买 nike

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

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

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

set -U LIGHT_COLORSCHEME (not $LIGHT_COLORSCHEME)

最佳答案

Does fish even have booleans?

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

But it has false and true commands

是的。这些命令分别返回 1 和 0。任何返回状态 != 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

(当然你也可以做一个“翻转”函数——不幸的是,“not”是一个对命令返回状态而不是变量值进行操作的关键字)

后者看起来像

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”的命令,它就会运行它!

要测试条件,请使用 test

关于 fish shell : flip a boolean value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761491/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com