Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!