Bash Scripts: Variables, if and Loops
A script is a file of commands that run one after another. Scripts automate boring jobs: backups, reports, deployments.
Any task you type more than twice can become a script: backups, reports, deployments. Scripts combine commands with variables, conditions and loops, and can run automatically on a schedule.
Example
$ cat > report.sh <<'EOF'
> #!/bin/bash
> # Count orders and errors in a log file
> LOG="${1:-logs/access.log}" # first argument, or this default
>
> if [ ! -f "$LOG" ]; then
> echo "No such file: $LOG"
> exit 1
> fi
>
> orders=$(grep -c "POST /orders" "$LOG")
> errors=$(grep -c '" 5[0-9][0-9] ' "$LOG")
> echo "Log: $LOG"
> echo "Orders: $orders"
> echo "Server errors: $errors"
>
> if [ "$errors" -gt 0 ]; then
> echo "Warning: check the server!"
> fi
> EOF
$ chmod +x report.sh
$ ./report.sh
Log: logs/access.log
Orders: 2
Server errors: 1
Warning: check the server!
$ ./report.sh missing.log
No such file: missing.logParts of a script
#!/bin/bash- the first line says which program runs the scriptNAME="value"- no spaces around=; use it as"$NAME"(keep the quotes)$(command)- put a command's output into a variable$1, $2- arguments;${1:-default}uses a default if none given[ -f file ]file exists,-dfolder exists,-gtgreater than,-eqequal
Loops
Example
$ for city in Delhi Mumbai Pune; do
> echo "Shipping to $city"
> done
Shipping to Delhi
Shipping to Mumbai
Shipping to Pune
$ for f in *.csv; do
> echo "$f has $(($(wc -l < "$f") - 1)) rows"
> done
products.csv has 5 rows
$ count=3
> while [ $count -gt 0 ]; do
> echo "Retrying in $count..."
> count=$((count - 1))
> done
Retrying in 3...
Retrying in 2...
Retrying in 1...Start scripts with
set -euo pipefail on the second line. Then the script stops at the first error instead of carrying on and causing damage.Key points
- Start with #!/bin/bash and make it executable.
- Variables, if and loops work like in other languages.
- Use set -euo pipefail for safety.
📝 Test yourself
1. What does the first line #!/bin/bash do?
2. Which is correct in bash?
3. Fill in the way to save a command's output in a variable:
orders=grep -c POST log)
