bash 脚本和单个命令行中的 IF 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39214207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:06:36  来源:igfitidea点击:

IF statement in script and in a single command line

bashif-statement

提问by 71GA

My script below checks for the instance of opened window in X server and it prints some info in the terminal depending on the state.

下面的脚本检查 X 服务器中打开的窗口的实例,并根据状态在终端中打印一些信息。

#!/bin/bash
if [[ -z $(xwininfo -tree -root | grep whatsapp | grep chromium) ]]
then
        echo "IT DOES NOT EXIST";
else
        echo "IT EXIST";
fi

When I try to rewrite this into a one line terminal command I do it like this:

当我尝试将其重写为一行终端命令时,我会这样做:

if -z $(xwininfo -tree -root | grep whatsapp | grep chromium); then echo "IT DOES NOT EXIST"; else echo "IT EXIST"; fi

this returns error and a wrong state...

这将返回错误和错误状态...

bash: -z: command not found
IT EXISTS

Does anyone have any advice? I tried asking the ShellCheckbut it says I have everything in order...

有人有建议吗?我尝试询问ShellCheck,但它说我已准备好一切...

采纳答案by 71GA

I got messed with an online bash code checker which stated that [[and ]]are not needed. This worked for me:

我弄乱了一个在线 bash 代码检查器,它指出[[并且]]不需要。这对我有用:

if [[ -z $(xwininfo -tree -root | grep whatsapp | grep chromium) ]]; then chromium --app=\"https://web.whatsapp.com/\"; fi & if [[ -z $(xwininfo -tree -root | grep skype | grep chromium) ]]; then chromium --app=\"https://web.skype.com/en/\"; fi & if [[ -z $(xwininfo -tree -root | grep Viber) ]]; then viber; fi

回答by Charles Duffy

Correctly following the advice from http://shellcheck.net/would have looked like the following:

正确遵循来自http://shellcheck.net/的建议看起来如下所示:

if xwininfo -tree -root | grep whatsapp | grep -q chromium; then
    echo "IT DOES NOT EXIST";
else
    echo "IT EXIST";
fi

...thus, in one-liner form:

...因此,以单行形式:

if xwininfo -tree -root | grep whatsapp | grep -q chromium; then echo "IT DOES NOT EXIST"; else echo "IT EXIST"; fi


See the wiki page for SC2143, the shellcheck warning you received.

请参阅SC2143的 wiki 页面,您收到的 shellcheck 警告。