As a DevOps engineer, I’ve often encountered with Bash. Doing something on a server, writing CI/CD pipelines, or automating some manual task are all regular activities that regularly include writing some Bash scripts. Here I’ll share my tips and best practices to follow when scripting in Bash.
Photo by Gabriel Heinzer on Unsplash
1. Distinguish variables
When it comes to variables in Bash, there are two well-known good practices.
- Always put curly brackets
{}around the variable name. - Always put double quotes
""around the variable.
Therefore, a variable should look like this: "${variable_name}" . This way variables are clearly distinguished from the rest of the code and spaces inside a variable value will not cause problems. Let’s illustrate the problem with spaces on an example.