I develop and maintain a bunch of bash shell scripts for my Raspberry Pi (e.g. downloading of files from list of urls, monitoring physical gpio power off switch etc.). I have to admit I did not pay close attention to designing them perfectly, I just wanted to get the job done. However, even in such a simple cases I have experienced myself kind of technical debt when something suddenly went wrong. It is always good to follow good design principles. Here I mean avoiding unnecessary dependencies between software modules. Even in such simple programs.
These are my quick observations of what to do and what not to do when writing either shell scripts or interpeter scripts under Unix/Linux environment.
- DO NOT USE DOT CHARACTER in script’s code. Use variables, assign them a value once and then refer to them in the code. Relying on external assumptions that script will be executed in certain directory is bad and will hurt. It is extremely likely you will forget the (in fact, unnecessary) requirements when executing script elsewhere, e.g. from cron.
- If you absolutely have to refer to some file located in the same directory as the script itself, consider writing another script whose solely purpose is to change the directory to meet target’s expectations and then immediately execute it. Although it would be strange to write shell script to execute another shell script, this technique can be used with other interepreted languages e.g. Python or Perl scripts.
- DO NOT USE TILDE CHARACTER in script’s code. It has not obvious expansion rules. For instance, it works at the beginning of the word, but not in the middle. That also means, it is very likely to forget the rules and have the tilde character not expanded in location where it is expected to. Use the value of
HOME
variable and expand it in one of traditional ways.