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

298
Visualizações
How to get success status of last Bash shell command inside a shell script?

Sometimes there are two commands which I often invoke in a row. However the second command only makes sense in case the first command was successful.

I wanted to do something like this:

#!/bin/bash

if [ $? -gt 0 ]
then
    echo "WARNING: previous command entered at the shell prompt failed"
fi

But it doesn't work:

t@quad:~$ echo "abc" | grep def
t@quad:~$ ./warnme.sh 
Last command succeeded

What I'd like is something a bit like this:

t@quad:~$ echo "abc" | grep def
t@quad:~$ echo ${PIPESTATUS[1]}
1

Where we can clearly see that the last command failed.

The result I'd like to have:

t@quad:~$ echo "abc" | grep def
t@quad:~$ ./warnme.sh 
WARNING: previous command entered at the shell prompt failed

I can't find a way to do it.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

command1 && command2

does exactly what you want: command 2 is executed only if command1 succeeds. For example you could do:

ls a.out && ./a.out

Then a.out would only be executed if it could be listed. I wikiblogged about this at http://www.linuxintro.org/wiki/%26%26

over 4 years ago · Santiago Trujillo Relatório

0

One option is to put this just before the list of commands you want to execute only if the previous was successful:

set -e

This will exit the script if any of the commands following it return non-zero (usually a fail). You can switch it off again with:

set +e

Or if you'd prefer to switch it off for just one line you can just logical-OR the command with true:

mycommand || true

For a lot of my scripts I have set -e at the top of the script as a safety feature to prevent the script cascading and doing something dangerous.

over 4 years ago · Santiago Trujillo Relatório

0

How about:

echo "abc" | grep def || ./warnme.sh

Where warnme.sh is now only the warning without the test. It's only called if the first command fails.

In other words, it would be the same as:

echo "abc" | grep def || echo "WARNING: That didn't work..."
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