Stop 02 · Linux & Command LineTopics · 6/11

Shell Scripting Basics (Bash)

Part of the DevOps 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.

Automating repetitive command-line tasks by writing Bash scripts — variables, loops, conditionals, and functions — the entry point into DevOps automation before reaching for a full programming language.

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 simple Bash script that automates a repetitive task (e.g. backing up a folder).
  2. 2Practice using variables, if/else conditionals, and a for loop in a script.
  3. 3Learn to make a script executable and run it directly rather than via `bash script.sh`.

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