Skip to content

Instantly share code, notes, and snippets.

@1stvamp
Last active October 25, 2024 11:07
Show Gist options
  • Save 1stvamp/2ab422c9a74186d1482b2793804c72ac to your computer and use it in GitHub Desktop.
Save 1stvamp/2ab422c9a74186d1482b2793804c72ac to your computer and use it in GitHub Desktop.
bash functions I use time and time again in scripts
#!/bin/bash
# Wrapper around apt/apt-get install to avoid all interactive prompts
function apt_install {
local DEBIAN_FRONTEND=noninteractive
local DEBIAN_PRIORITY=critical
export DEBIAN_FRONTEND DEBIAN_PRIORITY
sudo /usr/bin/apt-get install --yes --quiet --option Dpkg::Options::=--force-confold --option Dpkg::Options::=--force-confdef "$@"
return $?
}
# echo, but to STDERR
function echo_error {
>&2 echo "$@"
return $?
}
# tee, but sudo'd and no output
function sudo_tee {
# shellcheck disable=SC2068
sudo tee $@ >/dev/null
return $?
}
# Wrapper to retry a command so many times, waiting X+X seconds each time
# e.g. retry 5 5 some_command
# will run some_command at most 5 times, with a backoff starting at 5 seconds,
# then 10, 20, and 40 seconds.
function retry {
local RETRIES="$1"
local BACKOFF="$2"
local COMMAND="$3"
local EXIT_CODE=
set +e
# Run the command, and save the exit code
${COMMAND}
EXIT_CODE=$?
set -e
if [[ "${EXIT_CODE}" != 0 && "${RETRIES}" -gt 0 ]]
then
sleep "${BACKOFF}"
retry $(("${RETRIES}" - 1)) $(("${BACKOFF}" + "${BACKOFF}")) "${COMMAND}"
else
# Return the exit code from the command
return "${EXIT_CODE}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment