0

I have a large shell script that install a bunch of stuff. 9/10 times, it will work fine, however, it sometimes fails due to internet connectivity issues.

currently I have

apt-get install -y apache2 || { exit 1; }

and it works.

and I know that !! resembles the last command.

However, this does not work

apt-get install -y apache2 || { echo "!! Failed"; exit 1; }

I would expect the output, if failed, be:

apt-get install -y apache2 Failed

lastly, is there a way not to have the || { echo "!! Failed"; exit 1; } after every command.

Cripto
  • 3,581
  • 7
  • 41
  • 65
  • I guess it would be `echo !! "Failed"`. But `!!` will track the previous last command, not the one you just did before the pipe. – fedorqui Aug 13 '13 at 13:18

2 Answers2

1

In your script, say

set -e
# some arbitrary command
apt-get install -y apache2
# more commands

This would make the script exit if any subsequent command returns with non-zero exit code and would obviate the need of placing || exit besides every command in your script.

From the manual:

-e

Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a subshell command enclosed in parentheses (see Command Grouping), or one of the commands executed as part of a command list enclosed by braces (see Command Grouping) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !. A trap on ERR, if set, is executed before the shell exits.

This option applies to the shell environment and each subshell environment separately (see Command Execution Environment), and may cause subshells to exit before executing all the commands in the subshell.

devnull
  • 118,548
  • 33
  • 236
  • 227
0

Combining the information from this question, the following will work for BASH (and perhaps other shells as well):

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap 'if [ $? -ne 0 ]; then echo "$previous_command Failed"; fi' EXIT
set -e

Alternatively, you could use the built-in tracing, but this will print every command, not just the one that failed:

set -ex
Community
  • 1
  • 1
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98