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
In a nutshell
  • The first line #!/bin/bash selects the shell.
  • $NAME reads a variable, and $1 is the first argument.
  • if [ -d DIR ] tests for a directory, and -f tests 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.

Scriptcommands in ordersetsVariablesnames and pathsusesCommandsfiles, packages, usersproducesResultsystem changed

How it works

Look for the shell features first, then name the job that the commands do together.

Script building blocks

FeatureExampleMeaning
Shebang#!/bin/bashRun this file with Bash
Comment# backup stepIgnored by the shell
VariableDIR=/var/backupsStore a value. Read it with $DIR
Argument$1The first argument given to the script
Testif [ -d "$DIR" ]Check a condition
Loopfor f in *.logRepeat for each item
Exit status$?Result of the last command, where 0 means success

Useful tests

TestTrue when
-e PATHThe path exists
-f PATHIt is a regular file
-d PATHIt is a directory
-z TEXTThe text is empty
A = BThe two strings are equal
A -eq BThe 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

CommandSuggests
mkdir, cp, mv, rm, touchFile and directory management
cd, pwd, lsMoving around directories
apt, yum, dnf, pipInstalling software
useradd, usermod, userdel, passwdUser management
chmod, chownPermissions and ownership
systemctl start, systemctl enableStarting and enabling a service
curlCalling a web address or API
grep, cat, tailReading 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.

Exam tip

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/bash selects the shell.
  • $NAME reads a variable, and $1 is the first argument.
  • if [ -d DIR ] tests for a directory, and -f tests for a file.
  • for loops 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.

Watch out

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 DEST exists and is a directory.

  • What does an exit status of 0 mean?

    The last command succeeded.

  • A script runs apt install, useradd and systemctl 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.