Stop 02 · Linux & Networking BasicsTopics · 5/9

Bash Scripting for Automation

Part of the AWS Roadmap

In short

Typed the same five commands three days in a row? Put them in a file and run one command instead. That tiny habit is where every bit of automation starts.

Bash scripts automate repetitive tasks like installing software, rotating logs or running AWS CLI commands in sequence. Variables, loops, conditionals and exit codes are enough for most cloud automation.

The mascot sticks a note on a fridge door next to a watering can and a milk packet.

Think of it like this

The note for the house help

Before leaving for college, you write a note: 'Water the plants. If milk is over, buy two packets. Lock the door.' Anyone can follow it without calling you. A Bash script is that note for the computer: steps, a little 'if', and it runs while you sleep.

Watch it happen

How bash runs backup.sh

Shebang
Variables
if check
Loop
Exit code

1/5The first line #!/usr/bin/env bash tells Linux which program should run this file.

The big ideas

What you need to know

Start with a shebang

#!/usr/bin/env bash picks bash explicitly. Without it, your script may run in a different, simpler shell.

Quote your variables

Write "$FILE", not $FILE. Unquoted variables break on file names with spaces.

$1, $2 are arguments

./greet.sh Riya puts Riya in $1. $# counts arguments, so you can check they were given.

Exit codes matter

0 means success. $? holds the last command's code, and set -e stops the script on the first failure.

See it in code

Walk through the code

bash
1#!/usr/bin/env bash2set -euo pipefail3 4SRC="${1:?usage: backup.sh <folder>}"5DEST="/tmp/backups/$(date +%F)"6 7if [[ ! -d "$DEST" ]]; then8  mkdir -p "$DEST"9fi10 11for f in "$SRC"/*.conf; do12  cp "$f" "$DEST/"13  echo "copied $f"14done

1/4Pick bash, and make the script stop on errors, unset variables and failed pipes.

Run it with chmod +x backup.sh then ./backup.sh /etc/nginx. The date in the folder name keeps each day's backup separate.

Save yourself the pain

Common mistakes

Oops

Writing NAME = "Riya" with spaces, then getting 'command not found'.

Do this instead

No spaces around = in Bash. NAME="Riya" assigns, while NAME = runs a command called NAME.

Oops

Leaving variables unquoted, so a file called 'my notes.txt' becomes two files.

Do this instead

Always wrap variables in double quotes, like cp "$f" "$DEST".

Your mission

Your first useful script

~25 min

Quick check

What does set -e do at the top of a Bash script?

Go deeper

  1. 1Write a script that installs Nginx and starts it, which you will reuse as EC2 user data.
  2. 2Add set -euo pipefail at the top of your scripts and learn what each flag does.
  3. 3Write a loop that runs one command against a list of names read from a file.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge