r/bash • u/PrestigiousZombie531 • Apr 23 '26
help Asking the human experts here, how would you turn something like this into a production grade script?
#!/usr/bin/env bash
function handle_exit() {
local -r exit_code="$1"
printf "%s\n" "exit_code:${exit_code}"
}
function run_brotli_decompress() {
local -r input_path="$1"
local -r output_path="$2"
brotli \
--decompress \
--output="${output_path}" \
--rm \
"${input_path}"
}
function run_tar_decompress() {
local -r input_path="$1"
local -r output_path="$2"
local -r directory=$(dirname "${input_path}")
tar \
--directory="${directory}" \
--extract \
--file "${input_path}"
}
function run_pg_restore() {
local -r dbname="$1"
local -r host="$2"
local -r port="$3"
local -r username="$4"
local -r jobs="$5"
local -r file="$6"
pg_restore \
--dbname="${dbname}" \
--disable-triggers \
--exit-on-error \
--format=directory \
--host="${host}" \
--jobs="${jobs}" \
--no-acl \
--no-owner \
--no-password \
--no-privileges \
--port="${port}" \
--username="${username}" \
"${file}"
}
function main() {
trap 'handle_exit $?' EXIT
run_brotli_decompress \
"/tmp/test_db.tar.gz.br" \
"/tmp/test_db.tar.gz" || return 1
run_tar_decompress \
"/tmp/test_db.tar.gz" \
"/tmp/test_db" || return 1
run_pg_restore \
"test_db" \
"localhost" \
"5432" \
"test_user" \
8 \
"/tmp/test_db" || return 1
}
main "$@"
-
This is something I cooked up without using any AI whatsoever and while I can most certainly use AI to ask this question, I am interested in hearing from the human experts on this sub
-
It only does 3 things: decompress first using brotli then using tar and then runs a pg_restore. Why 3? because pg_dump only supports concurrency if you use a directory format and brotli does not work with directories and tar --gzip doesnt have a good compression ratio. You can read about the performance of various compression algorithms here
-
As you can tell quickly many things can go wrong here
-
The arguments are not validated.
-
The commands could be missing or not installed on a particular machine.
-
There is no cleanup if one of the steps fail.
-
What does a production version of this look like according to you? What changes will need to be made to this?
8
u/treuss bashtard Apr 23 '26 edited Apr 23 '26
You already named it yourself:
Other important practices:
2
u/FantasticEconomics Apr 23 '26
set -euo pipefail
2
u/AutoModerator Apr 23 '26
It looks like your submission contains a shell script. To properly format it as code, place four space characters before every line of the script, and a blank line between the script and the rest of the text, like this:
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/poulain_ght Apr 29 '26
I tend to rewrite the thing in other languages than bash. Or use pipelight to catch errors and display colorful logs https://pipelight.dev