Hi, Andrey. I have hundreds of shell scripts. If they look like junk, then I won't understand them or know how to use them if I haven't used them in a while.
Class A recommendations:
- Use a
main function
- Group related steps into functions
- Use function names that include a verb and clearly describe what the function does, so that comments become superfluous
- Put script name, version, purpose, and usage example at top of script
- Maximize simplicity and portability by avoiding
bashisms unless you absolutely need bash
- Keep user variables and internal script variables (i.e., ones user should not mess with) separate
- Use clear variable names that include a noun
- After your script is done, check it with
checkbashisms and
shellcheckClass B recommendations:
- Put main function at the top
- Use Allman braces style because it is trivial to use correctly (only rules are "each brace on its own line", "brace pairs equally indented")
I'm not sure what your script does, so I can't give the script or its functions good names. Here is a first attempt at cleaning it up. Note that this is rough
pseudocode that has several obvious errors and doesn't actually work (plus, its stated purpose and usage example are completely made up)--it's just to illustrate the principles:
#!/bin/sh
# dependency-checker v1.0
# Purpose: Find all of an extension's dependencies
# Usage example: $ dependency-checker brave-browser
# user variables:
log=/home/andrey/logs/dependency-checker.logs
main()
{
run_redo "$name" "$base"
echo "return {$(cat "${logs[@]}")}" > "$output"
}
run_redo()
{
local logs=( "$name.%d.log" )
for log in "${logs[@]}"; do
redo -l "$log" -m "$name" "$base" &
done
wait
}
# internal variables:
TNAME=${1##*/}
BNAME=${2##*/}
TDIR=${1%$TNAME}
main "$@"
I try my hardest to make my shell scripts beautiful.
The Pragmatic Programmer is the book that I have found to be the most helpful in this regard.