How to test if result of a command contains a string in fish shell?

我是研究僧i 提交于 2019-12-10 15:17:31

问题


I'm trying to write a brief function to allow me to toggle wemo lights on and off from the command line. Basically I have a command that if i type wemo status will return either Switch: Lights 1 if the lights are on or 0 if they are off. I'd like to write a fish function that essentially lets me toggle them:

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

Though this doesn't work. I'm thinking that the parens probably do a textual replacement? Anyone know how I can test if a string contains another string in Fish?


回答1:


contains seems to be to test if a list contains an element

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

Using command substitution, the list appears to be line-oriented:

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

Pattern matching the result using switch is a good choice.




回答2:


So I ended up fixing this with the following:

# 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


来源:https://stackoverflow.com/questions/21489086/how-to-test-if-result-of-a-command-contains-a-string-in-fish-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!