Shell脚本隐藏控制台消息?

时间:2011-08-10 19:22:08

标签: shell scripting

我很难从我在后台运行的shell(ksh)脚本中隐藏控制台消息。

我已经尝试将其移动到/ dev / null但它似乎没有工作。以下是脚本中的一行:

pid=`/usr/local/bin/lsof | grep 16752 | grep LISTEN |awk '{print $2}'` > /dev/null 2>&1

我开始播放剧本后的示例:

$ lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.
lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.

$ ls -lsof: WARNING: /home2/s499929/.lsof_ktazd2250 was updated.

关于我缺少的任何想法?

3 个答案:

答案 0 :(得分:3)

/usr/local/bin/lsof 2>/dev/null | grep 16752 | grep LISTEN |awk '{print $2}'

答案 1 :(得分:0)

也许您需要重定向实际lsof命令的输出而不是awk?

答案 2 :(得分:0)

您正在重定向变量赋值的输出。由于变量赋值不会产生任何输出,因此您的重定向没有做任何事情。

反引号捕获命令的标准输出;你需要重定向该命令的stderr,这意味着重定向需要在反引号之间。

我的第一个想法是这样做:

pid=`/usr/local/bin/lsof | grep 16752 | grep LISTEN | awk '{print $2}' 2>/dev/null`

但只重定向awk命令的stderr。您需要丢弃整个管道的stderr:

pid=`(/usr/local/bin/lsof | grep 16752 | grep LISTEN | awk '{print $2}') 2>/dev/null`

但我个人更喜欢$(...)反对:

pid=$((/usr/local/bin/lsof | grep 16752 | grep LISTEN | awk '{print $2}') 2>/dev/null)

(请注意,我只是重定向stderr,而不是stdout;你需要stdout来进行变量赋值。)