user11236651
user11236651

Reputation: 11

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

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

Answers (2)

Regretful
Regretful

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

Gordon Davisson
Gordon Davisson

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

Related Questions