Bash is the most widely used shell on Linux and a fundamental tool for every administrator. This guide takes you from your first script to advanced techniques.
Why Learn Bash?¶
Bash is the default shell on most Linux distributions. It is available practically everywhere — from servers to containers to CI/CD pipelines. Knowing Bash means the ability to automate anything on the command line.
Unlike Python, Bash is directly connected to the system. Running commands, working with files, and chaining tools is natural and fast.
First Script¶
Every Bash script starts with a shebang:
!/bin/bash¶
echo “Hello, world!” chmod +x script.sh ./script.sh
Variables¶
NAME=”server01” echo “Hostname: $NAME” echo “CPU count: $(nproc)”
- Local variables — valid in the current shell
- Exported — available in subprocesses (export VAR=value)
- Special — $?, $#, $@, $0, $$
Conditions¶
if [ -f “/etc/nginx/nginx.conf” ]; then echo “Nginx is installed” else echo “Nginx not found” fi if [[ “$OS” == “Linux” && -d “/proc” ]]; then echo “We are on Linux” fi
Loops¶
for f in /var/log/*.log; do echo “Processing: $f” wc -l “$f” done count=0 while [ $count -lt 5 ]; do echo “Iteration: $count” ((count++)) done
Functions¶
backup_dir() { local src=”$1” local dest=”$2” local date=$(date +%Y%m%d) tar czf “${dest}/backup-${date}.tar.gz” “$src” } backup_dir /etc /tmp
Error handling¶
set -euo pipefail trap ‘echo “Error on line $LINENO”; exit 1’ ERR die() { echo “FATAL: $*” >&2; exit 1; } [ -f “$CONFIG” ] || die “Configuration file not found”
- Always use set -euo pipefail
- Quotes: “$var”
- shellcheck for static analysis
- For 100+ lines consider Python
Bash Is Fundamental¶
Bash scripting is an essential skill. Start simple, use shellcheck, and gradually add complexity.