Created
February 5, 2018 14:59
-
-
Save jolbax/4a5ecb68e4ac6b62682fa9025982cedd to your computer and use it in GitHub Desktop.
Fail fast in case of errors
Lines 3–5 are related to handling erroneous situations. If any of the situations happen that these settings have effect on, they will exit the shell script and prevent it running further. They can be combined to set -ueo p
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -u # Exit if undefined variable is used. | |
set -e # Exit after first command failure. | |
set -o pipefail # Exit if any part of the pipe fails. | |
ITERATIONS=$1 # Notice that there are no quotes here. | |
shift | |
COMMAND=("$@") # Create arrays from commands. | |
DIR=$(dirname "$(readlink -f "$0")") # Get the script directory. | |
echo "Running '${COMMAND[*]}' in $DIR for $ITERATIONS iterations" | |
WORKDIR=$(mktemp --directory) | |
function cleanup() | |
{ | |
rm -rf "$WORKDIR" | |
} | |
trap cleanup EXIT # Make sure that we clean up in any situation. | |
for _ in $(seq 1 "$ITERATIONS"); do | |
( # Avoid the effect of "cd" command from propagating. | |
cd "$WORKDIR" | |
"${COMMAND[@]}" \ # Execute command from an array. | |
| cat | |
) | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment