How to get the Exit code from a command block

Asked

Viewed 183 times

1

Suppose I have the following commands in a script

susd
systemctl status firewalld

If I look at the exit code through echo $? it returns 0 because the last command was executed successfully, but how can I get the exit code of the whole block? in this my example should be an Exit code 1 or higher because susd there is no.

  • You can do a check for each command, since the $? captures the error of the last executed command, would be feasible for your case?

  • You can put your code in a function and use the $? to obtain the exit code of the same

2 answers

0

set -e

Forces completion of a pipeline execution (or sequence of commands) when an error occurs, so you can get Exit status through the $?

Reference: set

0

Probably not the best option, but you can create a function with the $? and call after each command to check the exit_code, something like:

#!/bin/bash

captura_erro(){
        if [ $? -eq 0 ]; then
                echo "Sucesso"
        else
                echo "Erro"
        fi
}

susd > /dev/null 2>&1
captura_erro
ls > /dev/null 2>&1
captura_erro
catinho > /dev/null 2>&1
captura_erro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.