Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda