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

时间:2016-08-29 19:58:26

标签: bash if-statement

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

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

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

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

这会返回错误和错误的状态...

bash: -z: command not found
IT EXISTS

有没有人有任何建议?我试着询问ShellCheck,但它说我把所有东西都按顺序......

2 个答案:

答案 0 :(得分:4)

正确地遵循http://shellcheck.net/的建议将如下所示:

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

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

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

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

答案 1 :(得分:0)

我搞砸了一个在线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