Pradyumna Krishna
Pradyumna Krishna

Reputation: 45

How to change output depending upon command exit status in shell?

I am working on a bash shell, While writing a script I thought to change the output and error massage of a command.

For Example the command is

sudo apt install nano

I want to give output

Installing nano

When command finishes successfully then

Nano Installed

Otherwise

Error occurred

While doing so I tried this

printf "\n Installing Nano"
{
  sudo apt install nano -y
} &> /dev/null
printf "\r Nano Installed \n"

but it not show distinct values for different exit status

Upvotes: 1

Views: 253

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125788

I think you're mixing up two different things, success vs. failure and stdout vs stderr. The stdout vs. stderr distinction really has to do with a command's "normal" output (stdout) vs. status messages (stderr, including error messages, success messages, status messages, etc). In your case, all of the things you're printing should go to stderr, not stdout.

Success vs failure is a different question, and it's generally detected by the exit status of the command. It's a bit strange-looking, but the standard way to check the exit status of a command is to use it as the condition of an if statement, something like this:

printf "\n Installing Nano" >&2
if sudo apt install nano -y &> /dev/null; then
    # The "then" branch runs if the condition succeeds
    printf "\r Nano Installed \n" >&2
else
    # The "else" branch runs if the condition fails
    printf "\r Error Occured  \n" >&2
fi

(Using && and || instead of if ... then ... else can cause confusion and weird problems in some situations; I do not recommend it.)

Note: the >&2 redirects output to stderr, so the above sends all messages to stderr.

Upvotes: 1

Pradyumna Krishna
Pradyumna Krishna

Reputation: 45

While Trying to do so i found out a way

printf "\n Installing Nano"
sudo apt install nano &> /dev/null &&
printf "\r Nano Installed\n" ||
printf "\r Error Occured\n"

I think this will work for all

Upvotes: 0

Related Questions