【问题标题】:How to test if result of a command contains a string in fish shell?如何测试命令的结果是否包含鱼壳中的字符串?
【发布时间】:2014-02-24 16:19:06
【问题描述】:

我正在尝试编写一个简短的函数,以允许我从命令行打开和关闭 wemo 灯。基本上我有一个命令,如果我输入wemo status,如果灯亮则返回Switch: Lights 1,如果灯灭则返回0。我想写一个鱼功能,基本上可以让我切换它们:

function lights --description 'Toggle lights'
    if contains (wemo status) "Lights 1"
        wemo switch "Lights" off
    else
        wemo switch "Lights" on
    end
end

虽然这不起作用。我在想括号可能会进行文本替换?任何人都知道我如何测试一个字符串是否包含 Fish 中的另一个字符串?

【问题讨论】:

    标签: terminal osx-mountain-lion fish


    【解决方案1】:

    所以我最终用以下方法解决了这个问题:

    # Toggle lights
    function lights --description "Toggle Wemo Lights"
        set -l wemo (wemo status)
        switch $wemo
            case '*1'
                wemo switch "Lights" off
            case '*0'
                wemo switch "Lights" on
        end
    end
    

    【讨论】:

    • 作为鱼的主要开发者,这是我的建议。如果您愿意,可以取消该变量:switch (wemo status)...
    【解决方案2】:

    contains 似乎是为了测试一个列表是否包含一个元素

    set elems foo bar baz
    contains bar $elems; and echo yep
    

    使用命令替换,列表看起来是面向行的:

    contains "e f"   (printf "%s\n" "a b c" "d e f" "g h i"); and echo y; or echo n
    contains "d e f" (printf "%s\n" "a b c" "d e f" "g h i"); and echo y; or echo n
    
    n
    y
    

    使用switch 匹配结果的模式是一个不错的选择。

    【讨论】:

    • 正确。 contains 的问题是它不处理通配符模式匹配。 contains opt\* $list 将无法按预期工作。另外,请记住不要忘记您的--,在检查带有前置连字符的符号时,例如contains -- -opt $list。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2017-11-21
    相关资源
    最近更新 更多