Bash scripting basics
Variables, conditionals, loops and making a script executable.
The shebang and making it executable
The first line tells the shell which interpreter to run the script with. chmod +x makes the file executable so you can run it directly instead of typing bash script.sh.
#!/usr/bin/env bash
echo "hello from a script"Variables
No spaces around =. Reference a variable with $NAME or ${NAME}; the braces are needed when concatenating right up against other text.
NAME="world"
echo "hello, ${NAME}!"Conditionals
if/then/fi with [[ ]] for the test β the double-bracket form is more forgiving than the classic single-bracket [ ] and is what modern scripts should use.
if [[ -f /etc/nginx/nginx.conf ]]; then
echo "nginx is installed"
else
echo "not found"
fiLoops
for iterates over a list of values; while repeats as long as a condition holds. Both are common in deploy and backup scripts for looping over files or hosts.
for f in /etc/nginx/sites-available/*; do
echo "found: $f"
doneFail fast
Add set -euo pipefail near the top of any real script: it exits on the first error, on use of an unset variable, and on a failure anywhere in a pipeline β instead of silently continuing after something breaks.
#!/usr/bin/env bash
set -euo pipefail