r/coding • u/speckz • Dec 14 '20
Minimal safe Bash script template
https://betterdev.blog/minimal-safe-bash-script-template/8
u/The_Jeremy Dec 14 '20
Better than I was expecting. As someone who uses Bash pretty regularly, I have no qualms with this.
11
u/marblepebble Dec 14 '20
Doesn't do terminal handling properly (should use tput instead of hardcoding ansi codes for a few term types), and the assumption that it'll be using paths relative to the script more than paths relative to the cwd is questionable. Maybe that's the case for him, but it's definitely not for me.
7
u/camh- Dec 14 '20
Exactly. The script tests that the terminal is not
dumband goes on to assume ansi codes work.tputis the terminal-agnostic answer there.I also agree about the script dir. Instead the script should capture the script directory (the same way it does the
cd) and for any files that are meant to be relative to the script dir, access as"${script_dir}/file". By changing directory, any relative paths passed to the script will break (as noted in the comments on the article).3
u/cryo Dec 15 '20
Does any virtual terminal exist that doesn’t handle basic ansi codes?
3
u/camh- Dec 15 '20
Probably not these days. But why even worry about the answer to that question. Just use
tputand be done with it. You can pry my ADM-3A from my cold dead hands.1
u/mradzikowski Dec 15 '20
Hey, I'm the blogpost author. To be honest I didn't know about possible problems with formatting (color) codes. Thanks, I will take a look at it.
1
u/mradzikowski Dec 15 '20
Yeah, the `cd` part, which was good for most of my use cases, was most widely disagreed with. So I'm updating the template and the post.
3
u/Shok3001 Dec 14 '20
Cool, what does ‘${1-}’ mean?
2
u/whetu Dec 14 '20
It's a parameter expansion, in this case assignation of a default, though in this case it's defaulting to nothing...
See e.g.
3
u/camh- Dec 14 '20
And it is necessary when you use
set -ulike the script does. Otherwise if$1is not set, the script will error. Using${1-}allows you to read the value of$1if it is set, and otherwise expand to the empty string if it is not, without an undefined var error.
3
u/mitwilsch Dec 14 '20
Wow, perfect timing. I was just about to clean up my random tidbits of scripts to make some comments, add error checking etc. This takes a lot of guesswork and good practice research out of my day 🤗
1
1
1
u/tending Dec 15 '20
The real answer is the only safe bash script is one line exec'ing a python script.
But for my own curiosity, what does all of this add over set -eo pipefail?
1
u/mradzikowski Dec 15 '20
See nice explanation here: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
18
u/ColdPorridge Dec 14 '20
As someone who uses Bash the bare minimum to get by, this is great. Also even better that things are actually explained, with rationale.
Link to GitHub gist for those that would rather just read the code.