Before Jenkins pipelines, Ansible playbooks and Terraform, there is the humble shell script. DevOps engineers use Bash every day to automate small jobs: checking disk space, rotating logs, deploying a build or restarting a service. Learning the basics makes every other tool easier.
Your first script
#!/bin/bash
echo "Disk usage on $(hostname):"
df -h /
Save it as check.sh, make it executable with chmod +x check.sh, and run it with ./check.sh. The first line (the shebang) tells Linux which interpreter to use.
Variables and arguments
APP_DIR="/opt/myapp"
echo "Deploying to $APP_DIR"
No spaces around =. Arguments passed to the script are available as $1, $2 and so on. Always wrap variables in double quotes so paths with spaces do not break your script.
Conditions
if [ -f "$APP_DIR/app.jar" ]; then
echo "Build found"
else
echo "Build missing"; exit 1
fi
-f checks for a file, -d for a directory, and -z for an empty string.
Loops
for server in web1 web2 web3; do
ping -c 1 "$server" > /dev/null && echo "$server up" || echo "$server down"
done
Exit codes
Every command returns an exit code: 0 means success, anything else means failure. $? holds the last one. CI/CD tools rely on exit codes to decide whether a stage passed, so your scripts should exit with a non-zero code when something goes wrong.
Safe habits
- Start scripts with
set -euo pipefailso they stop on errors and unset variables instead of carrying on silently. - Quote your variables.
- Test destructive commands such as
rmwithechofirst. - Run
shellcheckon your scripts; it catches many common mistakes.
Practise by writing a script that checks disk usage and prints a warning above 80 percent. Then read Linux commands every DevOps learner should know and CI/CD explained.
Linux and scripting labs are part of our AWS and DevOps course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
