Infrastructure and Automation · Topic 6 of 8
Interpreting a Bash Script
Read a Bash script and identify the workflow it automates, from variables, tests and loops to file handling, package installs, users and directory changes.
- 4 min
- The first line
#!/bin/bashselects the shell. $NAMEreads a variable, and$1is the first argument.if [ -d DIR ]tests for a directory, and-ftests for a file.
What it is
A Bash script is a text file of shell commands that run in order, with variables, conditions and loops added.
To interpret one, you read the commands in sequence and say what the script achieves. The usual jobs are file handling, installing an application, managing users and moving through directories.
The first line, #!/bin/bash, tells the system to run the file with Bash.
How it works
Look for the shell features first, then name the job that the commands do together.
Script building blocks
| Feature | Example | Meaning |
|---|---|---|
| Shebang | #!/bin/bash | Run this file with Bash |
| Comment | # backup step | Ignored by the shell |
| Variable | DIR=/var/backups | Store a value. Read it with $DIR |
| Argument | $1 | The first argument given to the script |
| Test | if [ -d "$DIR" ] | Check a condition |
| Loop | for f in *.log | Repeat for each item |
| Exit status | $? | Result of the last command, where 0 means success |
Useful tests
| Test | True when |
|---|---|
-e PATH | The path exists |
-f PATH | It is a regular file |
-d PATH | It is a directory |
-z TEXT | The text is empty |
A = B | The two strings are equal |
A -eq B | The two numbers are equal |
Example 1: file management and backup
#!/bin/bash
SRC=/home/user/project
DEST=/var/backups
if [ ! -d "$DEST" ]; then
mkdir -p "$DEST"
fi
cp -r "$SRC" "$DEST/project_backup"
cd "$DEST"
ls -l
This script sets two paths. It creates the backup folder if it does not exist, copies the project into it, moves into the folder and lists it. The workflow is back up a project folder.
Example 2: application install and user creation
#!/bin/bash
APP=nginx
sudo apt update
sudo apt install -y "$APP"
sudo useradd -m deploy
sudo systemctl enable "$APP"
sudo systemctl start "$APP"
The commands refresh the package list, install nginx without asking, create a user with a home directory, and enable and start the service. The workflow is install a web server, add a deploy user and start the service.
Example 3: a loop and log handling
#!/bin/bash
for f in /var/log/app/*.log; do
if [ -f "$f" ]; then
gzip "$f"
mv "$f.gz" /var/log/archive/
fi
done
echo "Logs archived"
The loop goes through every log file, compresses it, moves the result into an archive folder and prints a message at the end. The workflow is compress and archive log files.
Example 4: an argument and an exit check
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: deploy.sh VERSION"
exit 1
fi
cd /opt/app || exit 1
git pull
echo "Deployed version $1"
The script needs an argument. It prints a usage message and stops with a non zero status if none is given.
It then changes to the application folder, pulls the latest code and reports. The workflow is update an application from Git.
Commands that give strong clues
| Command | Suggests |
|---|---|
mkdir, cp, mv, rm, touch | File and directory management |
cd, pwd, ls | Moving around directories |
apt, yum, dnf, pip | Installing software |
useradd, usermod, userdel, passwd | User management |
chmod, chown | Permissions and ownership |
systemctl start, systemctl enable | Starting and enabling a service |
curl | Calling a web address or API |
grep, cat, tail | Reading and searching text |
Quoting and variables
Variables are expanded inside double quotes, and not inside single quotes. Wrap variables in double quotes to cope with spaces in names. There must be no spaces around the equals sign in an assignment.
Exit status and safe scripts
A command returns status 0 on success and a non zero value on failure. exit 1 stops the script with an error. Adding set -e near the top stops the script at the first failing command.
Name the job in one sentence. Look at what changes: files, packages, users or services.
What to remember for the exam
Six facts cover this topic.
- The first line
#!/bin/bashselects the shell. $NAMEreads a variable, and$1is the first argument.if [ -d DIR ]tests for a directory, and-ftests for a file.forloops repeat a block of commands, once for each item.- An exit status of 0 means success, and a non zero status means failure.
- Package, user and service commands tell you the kind of job the script automates.
Common mistakes
Four mistakes are typical.
Putting spaces around the equals sign. DIR = /tmp fails, because Bash treats DIR as a command.
Using single quotes around a variable. The variable is not expanded.
Forgetting to make the script executable. Run chmod +x script.sh or start it with bash script.sh.
Skipping error checks. A script that carries on after a failed cd may act in the wrong folder.
A script with rm -r on a variable that turns out empty can delete far more than intended. Check variables first.
Check yourself
Work through these three questions.
What does
if [ -d "$DEST" ]test?Whether the path held in
DESTexists and is a directory.What does an exit status of 0 mean?
The last command succeeded.
A script runs
apt install,useraddandsystemctl start. What kind of job is it?It installs an application, creates a user and starts a service.
Topic 6 of 8 in Infrastructure and Automation
Test yourself on Infrastructure and Automation
The full Cisco CCNA 200-901 DEVASC question bank has 808 questions, with timed practice exams and an explanation for every answer.
This study guide is independent and is not affiliated with, endorsed by, or sponsored by Cisco. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.