Lesson 1 of 7 · 9 min · Bash basics

Your first script: variables, quoting and expansion

Covers: Ubuntu 24.04 LTS, bash 5.2. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • What a script is, the shebang line, and how to make it executable
  • Variables, command substitution and arithmetic
  • Positional parameters ($1, $@, $#) and default values
  • Quoting rules: why "$var" is the habit that saves you
  • Arrays and string tricks you will use in real scripts

In simple words

A script is a list of commands saved in a file, so the computer can repeat them exactly whenever you ask. It is like writing down the steps of a job once instead of explaining them every day. This lesson writes a first script and covers the one habit that prevents most script bugs: putting quotes around variables.

Words to know

  • Script: a text file of commands that run one after another.
  • Shebang: the first line (#!/bin/bash). It says which program should run the file.
  • Variable: a named box that holds a value, such as name="Asha".
  • Quoting: wrapping text in quotes so the shell treats it as one piece, spaces included.

Why scripts

Everything a DevOps engineer does twice should become a script: deploys, backups, health checks, cleanup, glue between tools. A shell script is a text file of commands that the shell runs in order, plus variables, conditions and loops. It is not the best language for large programs (use Python for those), but it is unbeatable for gluing commands together, and it is everywhere: CI pipelines, Dockerfiles, ExecStart lines, cron jobs.

The smallest script

Create hello.sh:

#!/usr/bin/env bash
name="Asha"
count=3
echo "Hello, $name. You have $count new messages."
  • The first line is the shebang. It tells the kernel which program runs the file. #!/usr/bin/env bash finds Bash on the PATH, which works on systems where it is not in /bin. It must be the very first line.
  • Make it executable and run it: chmod +x hello.sh && ./hello.sh. Or run it explicitly without the bit: bash hello.sh.
  • # starts a comment.
Hello, Asha. You have 3 new messages.

Assignments have no spaces around =. name = "Asha" makes Bash try to run a command called name. Read the variable with $name or ${name}; use braces when text follows directly: ${name}_backup.

Command substitution and arithmetic

today=$(date +%F)                   # capture a command's output
echo "Today is ${today}"
echo "Next year: $(( $(date +%Y) + 1 ))"   # $(( )) is integer arithmetic
Today is 2026-11-12
Next year: 2027

Use $( ), not the older backticks: it nests and reads better. Bash arithmetic is integers only. For decimals use bc or awk.

Quoting: the most important section

The shell expands things before running a command, and then splits the result into words at spaces. Quotes control this.

Form What happens
'single' everything literal; no expansion at all
"double" $var, $(cmd) and $((...)) expand, but the result is not split into words
no quotes expansions happen and the result is split at whitespace and may be turned into file names (globbing)
echo 'Single quotes keep $name literal'
Single quotes keep $name literal

The classic bug. A file called my file.txt:

touch "my file.txt"
ls -l my file.txt        # two arguments: "my" and "file.txt"
ls: cannot access 'my': No such file or directory
ls: cannot access 'file.txt': No such file or directory

and the fix is ls -l "my file.txt". In a script the name often comes from a variable, so the rule is:

Always put double quotes around variable expansions: "$var", "$(cmd)", "$@", unless you specifically want splitting.

Unquoted, rm -rf $dir/* with an empty dir becomes rm -rf /*. Quoted and guarded, rm -rf "${dir:?}"/* stops with an error if dir is empty. The tool ShellCheck warns about unquoted expansions (lesson 3).

Arguments to a script

echo "script name: $0, first arg: ${1:-none}, all args: $*, count: $#"

Run ./hello.sh one two:

script name: hello.sh, first arg: one, all args: one two, count: 2
Variable Meaning
$0 the script's name
$1, $2... the arguments
$# how many arguments
"$@" all arguments, each kept as its own word (use this one)
$* all arguments joined; rarely what you want
$? exit code of the last command
$$ the script's PID

Defaults and required values

Parameter expansion has shortcuts that appear in every real script:

region="${REGION:-ap-south-1}"       # use $REGION, or this default if unset or empty
: "${DB_PASSWORD:?DB_PASSWORD must be set}"   # stop with an error if missing
region=ap-south-1

Trimming and replacing text in a variable, with no extra programs:

str="deploy-v1.2.3.tar.gz"
echo "${str%.tar.gz}"    # remove the shortest match from the end:   deploy-v1.2.3
echo "${str#deploy-}"    # remove from the start:                    v1.2.3.tar.gz
echo "${str//./_}"       # replace every dot:                        deploy-v1_2_3_tar_gz
echo "${#str}"           # length:                                   20

Environment variables

A variable lives only in the current shell unless it is exported: export APP_ENV=prod makes it visible to programs the script starts. Variables set on the same line apply to one command only: APP_ENV=test ./run-tests.sh. Inspect everything exported with env. Never print secrets into logs.

Arrays

arr=(web db cache)
echo "first=${arr[0]} all=${arr[*]} n=${#arr[@]}"
for s in "${arr[@]}"; do echo "svc: $s"; done
declare -A port=([web]=80 [db]=5432)    # associative array (Bash 4+)
echo "db port ${port[db]}"
first=web all=web db cache n=3
svc: web
svc: db
svc: cache
db port 5432

"${arr[@]}" keeps each element as one word, even if it contains spaces. Plain sh and dash have no arrays; that is one reason to use #!/usr/bin/env bash rather than #!/bin/sh when you need them.

bash, sh and portability

On Ubuntu /bin/sh is dash, a small POSIX shell without arrays, [[ ]] or (( )). Alpine containers use BusyBox ash and often do not have Bash at all. If a script says #!/bin/sh it must stick to POSIX features; if it needs Bash features it must say bash, and the image must contain Bash.

Common mistakes

  • Spaces around = in an assignment.
  • Unquoted variables that contain spaces or are empty.
  • Using $* instead of "$@".
  • Single quotes when you wanted expansion, and double quotes when you wanted it literal.
  • #!/bin/sh with Bash-only syntax, which works on your laptop and fails in Ubuntu's CI because sh is dash.
  • Forgetting the execute bit (Permission denied) or Windows line endings (bad interpreter: /usr/bin/env^M). Convert with dos2unix.

Try it yourself

  1. Write greet.sh that takes a name as the first argument, defaults to "world", and prints a greeting plus the current date.
  2. Create a file with a space in its name and show the failure and the fix with ls.
  3. Write a script that prints how many arguments it received and each one on its own line, correctly even for arguments containing spaces.
  4. Using only parameter expansion, turn backup-2026-11-12.tar.gz into backup-2026-11-12 and then into 2026-11-12.

Check yourself

What does the shebang line do, and why #!/usr/bin/env bash?

It tells the kernel which interpreter should run the file. env finds bash on the PATH, so it works even if Bash is not at /bin/bash (for example on NixOS, macOS with a newer Bash, or minimal containers).

What is the difference between $* and "$@"?

"$@" expands to each argument as a separate word, preserving spaces inside arguments. $* (and "$*") merges them, which breaks arguments that contain spaces.

Why is rm -rf $dir/* dangerous?

If dir is empty or unset, it becomes rm -rf /*. Quote it and guard it: rm -rf "${dir:?dir is not set}"/*.

What does ${VAR:-default} do and how does ${VAR:?message} differ?

:- substitutes the default if the variable is unset or empty. :? aborts the script with the message in that case.

Interview questions

What is the difference between single and double quotes in Bash?

Single quotes preserve everything literally. Double quotes allow variable, command and arithmetic expansion but prevent word splitting and globbing of the result.

What does export do?

It marks a variable for inheritance by child processes. Without it a variable is visible only inside the current shell.

How do you pass all arguments of your script to another command safely?

other-command "$@".

Summary

  • A script is a file with a shebang, made executable; run it with ./script.sh or bash script.sh.
  • Assign with no spaces, read with $var, capture output with $(...), calculate with $(( )).
  • Quote every expansion ("$var", "$@"); use ${var:-default} and ${var:?error} for defaults and required values.
  • Know the difference between Bash and POSIX sh.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Shell scripting with Bash for DevOps Engineer and scores every answer, with what to fix.