Creating Reusable Bash Scripts
Bash is a language that is quite useful for automation no matter what language
you write in. Bash can do so many powerful system-level tasks. Even if you are
on windows these days you are likely to come across bash inside a cloud VM,
Continuous Integration, or even inside of docker.
I have three techniques that help me write more composable bash scripts.
- functions [1]
- Arguments [2]
- positional arguments [3]
- All Arguments [4]
- Error Handling [5]
- main script [6]
---
Functions # [1]
Break scripts down into reusable components
Functions in bash are quite simple. They are something that I wish I would have
started using long ago. They make your code much more reusable. I often use
them in my aliases as well since they can simplify the process and allow more
flexibility.
syntax
#!/bin/sh
# hello_world
hello_world () {
echo "hello world"
}
Source the file to load the function and run it from the terminal.
run it
source hello_world
hello_world
outputs
hello world
...