2 ms·
Pro-protip tip: Add $0 but don't do pattern expansion. Worst case it's just slightly more verbose output. Best case, it's simpler to understand & maintain, and
by 0xbadcafebee 6y ago
Pro-protip tip: Add $0 but don't do pattern expansion. Worst case it's just slightly more verbose output. Best case, it's simpler to understand & maintain, and showing the path to your script will help unfamiliar people locate it quicker for debugging. (& I think it looks cleaner)
Also, don't run a command that directly overwrites a file unless you know it's going to succeed. A temp file lets you atomically replace the file only if the download succeeded. And a cleanup trap helps clean this up in the event of errors. Finally, you can die on unset variables or errors (cleanup still works) and you can enable tracing if environment variable DEBUG=1 was set.
#!/usr/bin/env sh
set -eu
[ "${DEBUG:-0}" = "1" ] && set -x
cleanup() { rm -f /usr/local/bin/mybinary.tmp ; } ; trap cleanup EXIT
panic() { printf "$0: Error: %s\n" "$1" >&2; exit 1; }
mkdir -p /usr/local/bin
[ -e /usr/local/bin/mybinary ] || \
wget -q -O /usr/local/bin/mybinary.tmp "$url" \
|| panic "wget was unable to download '$url'"
mv -f /usr/local/bin/mybinary.tmp /usr/local/bin/mybinary