Simple notes, commands, and practical examples for learning Bash as part of a DevOps journey.
Bash is a command-line shell used on Linux and macOS. In DevOps, it helps automate repetitive work such as backups, deployments, log checks, and server maintenance.
Create a file called hello.sh:
#!/usr/bin/env bash
echo "Hello, DevOps!"Make it executable and run it:
chmod +x hello.sh
./hello.sh| Command | What it does |
|---|---|
pwd |
Shows the current folder. |
ls -la |
Lists files, including hidden files. |
cd folder-name |
Moves into a folder. |
mkdir project |
Creates a folder. |
touch file.txt |
Creates an empty file. |
cp source target |
Copies a file. |
mv old new |
Moves or renames a file. |
rm file.txt |
Deletes a file. Use carefully. |
cat file.txt |
Prints a file's contents. |
grep "text" file.txt |
Finds text in a file. |
#!/usr/bin/env bash
NAME="Ada"
echo "Hello, $NAME"
echo "Enter your environment:"
read -r ENVIRONMENT
echo "Deploying to $ENVIRONMENT"Use arguments when running a script:
#!/usr/bin/env bash
echo "Application: $1"
echo "Environment: $2"./deploy.sh my-app stagingCheck whether a file exists:
if [ -f "config.yml" ]; then
echo "Configuration found"
else
echo "Configuration missing"
fiLoop through files:
for file in *.log; do
echo "Checking $file"
doneFunctions keep scripts organised and reusable.
say_hello() {
echo "Hello, $1!"
}
say_hello "DevOps learner"#!/usr/bin/env bash
df -h#!/usr/bin/env bash
SOURCE="./app-data"
BACKUP="backup-$(date +%F).tar.gz"
tar -czf "$BACKUP" "$SOURCE"
echo "Created $BACKUP"#!/usr/bin/env bash
SERVICE="nginx"
if systemctl is-active --quiet "$SERVICE"; then
echo "$SERVICE is running"
else
echo "$SERVICE is not running"
fi- Start scripts with
#!/usr/bin/env bash. - Add
set -euo pipefailnear the top of important scripts to stop on common errors. - Always quote variables: use
"$FILE", not$FILE. - Use clear variable names such as
BACKUP_DIRandLOG_FILE. - Add comments to explain why a command is needed.
- Test scripts in a safe environment before using them on production servers.
- Never put passwords, API keys, or tokens directly in a script or Git repository.
- Use
shellcheck script.shto find common Bash mistakes.
# File permissions
chmod +x script.sh # make executable
chmod 644 file.txt # read/write owner; read everyone else
# Redirect output
command > output.txt # save output (overwrite)
command >> output.txt # save output (append)
command 2> errors.txt # save errors
# Pipes
ps aux | grep nginx # find a process
cat app.log | tail -n 20 # show last 20 lines
# Archive files
tar -czf archive.tar.gz folder/
tar -xzf archive.tar.gzBash is commonly used to automate server setup, deployment tasks, CI/CD jobs, backups, monitoring checks, and log analysis.
Learning by building: each script in this repository is a small step toward reliable automation.