Reputation: 11
I need to do something like:
while true
do
if ss --tcp --processes | grep 53501 ; then <save result to /tmp/cmd.out> ; fi
done
Upvotes: 1
Views: 887
Reputation: 335
The while
loop looks dangerous, eventually you will run out of disk space.
while true
do
ss --tcp --processes | grep 53501 &>> /tmp/cmd.out
sleep 1
echo "Careful about using while true without any sleep"
done
&>>
pipes and appends all STDERR and STDOUT to file, naturally the output will be nothing if grep finds nothing.
Upvotes: 1
Reputation: 125998
It's inherently impossible to do exactly this, because a command (or pipeline of commands) produces output as it runs, but doesn't produce an exit status (success/failure) until it's finished running; therefore, you can't decide whether to save the output or not until it's already finished being output.
What you can do is store the output somewhere temporary, and then either save that or not. I'm not sure if this is quite what you're trying to do, but maybe something like this (using a variable as the temporary storage):
while true
do
output=$(ss --tcp --processes | grep 53501)
if [ -n "$output" ]; then
echo "$output" >/tmp/cmd.out
fi
done
Upvotes: 2