如何将 if 语句中命令的结果保存到文本文件

how-to save result of a command in an if statement to a text file

我需要做类似的事情:

while true
do 
   if  ss --tcp --processes | grep 53501 ; then <save result to /tmp/cmd.out> ; fi
done

完全这样做本质上是不可能的,因为命令(或命令管道)在运行时会产生输出,但不会产生退出状态(success/failure) 直到完成 运行;因此,在输出完成之前,您无法决定是否保存输出。

您可以做的是将输出临时存储在某个地方,然后保存或不保存。我不确定这是否正是您想要做的,但也许是这样的(使用变量作为临时存储):

while true
do 
    output=$(ss --tcp --processes | grep 53501)
    if [ -n "$output" ]; then
        echo "$output" >/tmp/cmd.out
    fi
done

while 循环看起来很危险,最终你会 运行 磁盘 space。

while true
do 
ss --tcp --processes | grep 53501 &>> /tmp/cmd.out
sleep 1
echo "Careful about using while true without any sleep"
done

&>> 管道并将所有 STDERR 和 STDOUT 附加到文件,如果 grep 什么也找不到,自然输出将是空的。