bash 带有空白/空 grep 的语句返回吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7922854/
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-09 21:08:35  来源:igfitidea点击:

While Do Statement with blank/empty grep return?

bashshellwhile-loopif-statement

提问by bikerben

This is the code for my foobar.sh:

这是我的 foobar.sh 的代码:

!#/bin/bash
while [ 1 ]
do
    pid=`ps -ef | grep "mylittleprogram" | grep -v grep | awk ' {print }'`
    echo $pid
    if [ "$pid"="" ]
    then
            echo "Process has ended lets get this show on the road..."
            exit
    else
            echo "Process has not ended yet"
    fi
    sleep 6
done

I'm basically running a infinate loop which will execute command X once a monitored process has ended but I end up getting the following message as my script loops:

我基本上正在运行一个无限循环,一旦受监控的进程结束,它将执行命令 X 但我最终在脚本循环时收到以下消息:

./foobar.sh: line 7: [: missing `]'
Process has not ended yet

Is there a way of making the script accept that zero feed back will trigger my 'Then' statement and execute command X since it is not liking the current method.

有没有办法让脚本接受零反馈将触发我的“Then”语句并执行命令 X,因为它不喜欢当前的方法。

回答by A.H.

Instead of

代替

if [ "$pid"="" ]

please try

请尝试

if [ "$pid" = "" ]

The whitespace is around =is important.

周围的空白=很重要。

You can also try

你也可以试试

if [ -z "$pid" ]

回答by sehe

I'd do

我会做

while pgrep -fl "mylittleprogram"; do sleep 6; done
exit # process has ended

(pgrep is in package psmiscIIRC)

(pgrep 在psmiscIIRC包中)

I've just tested it. You could redirect the output of pgrepto /dev/nullif you wanted the waiting to be silent. Add some more spice to make things uninterruptible:

我刚刚测试过了。如果您希望等待静默,您可以将pgrepto的输出重定向/dev/null。添加一些更多的香料,使事情不间断:

{
     trap "" INT
     while pgrep -fl "mylittleprogram" >/dev/null
     do 
         sleep 6
     done
     true
} && exit

回答by chx

The zero test is if [ -z "$pid" ]

零测试是 if [ -z "$pid" ]

回答by JRFerguson

Instead of the nebulous matching provided by:

而不是提供的模糊匹配:

pid=`ps -ef | grep "mylittleprogram" | grep -v grep | awk ' {print }'`

...and the archaic backtick syntax, consider this which matches the process basename exactly and produces an output format of your choice (here, the process pid if it exists):

...以及古老的反引号语法,请考虑这与进程基本名称完全匹配并生成您选择的输出格式(此处为进程 pid,如果存在):

pid=$(ps -C mylittleprogram -opid=)

Then, as noted, simply test for an empty value:

然后,如前所述,只需测试一个空值:

[ -z "${pid" ] && echo "no process" || echo "I live as $pid"

The equal sign following the output element name suppresses the heading that you would normally get. Manpages are your friend.

输出元素名称后面的等号抑制了您通常会得到的标题。联机帮助页是您的朋友。