Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check exit code in bash in one line/statement?

Tags:

bash

This is what I'm trying to do:

#!/bin/bash
set -e # I can't remove this line!

if [ docker inspect foo ]; then
  echo container is present
else
  echo container is absent
fi

Is it possible? docker inspect foo returns exit code 1 when container is absent and 0 when it's present.

Now I'm getting this:

-bash: [: too many arguments
like image 323
Uli Kunkel Avatar asked Mar 28 '15 01:03

Uli Kunkel


People also ask

How do I exit one in bash?

How can you exit a Bash script in case of errors? Bash provides a command to exit a script if errors occur, the exit command. The argument N (exit status) can be passed to the exit command to indicate if a script is executed successfully (N = 0) or unsuccessfully (N != 0).

How do I display exit status in last command?

The echo command is used to display the exit code for the last executed Fault Management command.

How do you break a long line in bash?

To split long commands into readable commands that span multiple lines, we need to use the backslash character (\). The backslash character instructs bash to read the commands that follow line by line until it encounters an EOL.


1 Answers

If you want to run the command within the "if" statement, you'd do it like this:

if docker inspect foo
then
  echo container is present
else
  echo container is absent
fi

All of the line breaks can be omitted or replaced by semicolons if you want. This would also work:

if docker inspect foo; then echo container is present; else echo container is absent; fi

If you want something more compact, you could use this kind of syntax:

docker inspect foo && echo container is present
docker inspect foo || echo container is absent
docker inspect foo && echo container is present || echo container is absent

&& runs the second command if the first succeeded. || runs the second command if the first one failed. The last line uses both forms.

like image 119
Kenster Avatar answered Nov 15 '22 18:11

Kenster