Shell scripting template
Once every week or so, I’ve to quickly write up some script(s) to automate something, have more control over a workflow, write a tool, etc. There is a common theme that emerges:
- Just write all the commands I need to run line by line in the script
- Wrap the above logic with conditionals or other logic based on the what I need to get done
- Handle error management gracefully i.e. throw meaningful error messages and/or redirect to a log file or something.
So in this blog post, I’ll write a simple script that does all of this.
main.sh
|
|
scrip1.sh
|
|
script2.sh
|
|
lib.sh
|
|
Here’s what happens when I run main.sh:
|
|
All the code is here.
Some key takeaways:
- Always use exit codes (0 for success). This is fairly common in unix systems and in C to communicate success/failure across different components
- Use library functions and import if possible
- Use error management and AND/OR operators to exit early (if that’s what you need)
You can read more about writing shell scripts here.