Shell scripting is like a room full of power tools: handy but dangerous.
Build complex systems. There are just too many ways that
external state can affect any piece of shell code. Do you know what your
script will do if you change
IFSbefore running it? What if you give it a file name starting with a dash or containing a newline? How do you recover the state of the system if the script crashed somewhere in the middle? Complex shell script environments invariably end up looking like Rube Goldberg machines of chainsaws and power drills. Use languages and frameworks appropriate for the task.
- Expose them to the Internet. Safe input handling is just too damn hard. Unless you’re GreyCat or Stéphane Chazelas.
eval. Don’t be evil. There are safer ways to do whatever you’re trying to do.
Write portable code. (By this I mean code which
works in multiple shells without change, as opposed to code which
can easily be ported to other shells.) Writing portable code means
limiting what language features you use and adding complexity to
make sure it works the same way in all the supported shells. Because of
this, the end result will be more complex and less flexible than
the simplest script that supports the shell you have.
- Minimise the number of characters. The next maintainer will hate you.
Create interactive menus. Very few shell tools like
toponly make sense interactively. Use command-line arguments instead, so that your tool will be useable both standalone and with other tools.
- Test everything automatically. This gives you and others the confidence that your script actually works. Bonus: Allows you to modify your code without having to test everything manually. Extra bonus: Experiencing how difficult it is to test shell scripts exhaustively will convince you to never use them for anything complex.
-toption. And if you can bear the screams of dogmatic developers, don’t support short options at all. As long as the names make sense this allows people to write readable scripts. Bonus: No wondering whether
-n5f0is two, three or four options.
Use guard statements like the POSIX
set -o errexit -o noclobber -o nounset. While there are some caveats to how these work, they can save a whole lot of headache. Bonus: Use
-o xtraceto see what the script does in detail.
- Add an auto-complete script. The users will be grateful. Bonus: Gives an incentive to keep the structure of your options sane.
No webmentions were found.