Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

299
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda