Created
September 16, 2021 17:54
-
-
Save jamesbursa/bf3a50fdb0cb348f6416ec3be1008634 to your computer and use it in GitHub Desktop.
Bash functions and scripts
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
#!/usr/bin/env bash | |
# | |
# Example script structure. | |
# | |
set -o errexit -o pipefail | |
source "$(dirname "$0")/util" | |
main() { | |
... | |
} | |
main |
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
print_log() { | |
printf "$CYAN%s $GREEN%s: $END%s\\n" "$(date "+%Y-%m-%d %H:%M:%S")" "$PROGRAM_NAME" "$*" | |
} |
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
run_command() { | |
print_log "run_command: $*" | |
# Use short options to `nl` for MacOS compatibility: | |
# -s = separator, -ba = number all lines | |
if "$@" | nl -s" │ " -ba | |
then | |
: | |
else | |
status=$? | |
print_log "$1 failed with exit status $status" | |
exit $status | |
fi | |
} |
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
run_sql() { | |
print_log "run_sql: $1" | |
PGPASSWORD=$DB_PASSWORD \ | |
psql --host="$DB_HOST" \ | |
--username="$DB_USERNAME" \ | |
"$DB_NAME" \ | |
--command="$1" | |
} | |
run_sql_output() { | |
print_log "run_sql_output: $1 -> $2" | |
PGPASSWORD=$DB_PASSWORD \ | |
psql --host="$DB_HOST" \ | |
--username="$DB_USERNAME" \ | |
"$DB_NAME" \ | |
--command="$1" \ | |
--no-align --field-separator=" " \ | |
--output="$2" | |
} |
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
PROGRAM_NAME=$(basename "$0") | |
CYAN='\033[96m' | |
GREEN='\033[92m' | |
END='\033[0m' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment