Variables, Quoting, and the Environment

How Bash variables really work: assignment rules, quoting and word splitting, parameter expansion, exporting to child processes, PATH lookup, and loading .env files.

By The Dark DebuggerUpdated 29 min read

This article covers shell variables from the ground up: how to assign them, how quoting decides what happens to their values, the parameter expansions that let you edit strings without external tools, and how variables reach other programs through the environment, including PATH. You should be comfortable at the prompt and with globbing from Wildcards, Globbing, and Brace Expansion, because unquoted variables get globbed. It opens the Shell Fundamentals section and is the foundation for Redirection and Pipes and every scripting article after it.

Why this matters

Two bugs account for a large share of broken shell scripts. The first is the script that works for months and then fails the day a file name contains a space, because a variable was used without quotes. The second is the deploy script that sets DB_HOST and then starts the application, which never sees the value because it was not exported.

Both come from not knowing exactly what the shell does with a variable. That is what this article is about. Every example below is something you can paste into a terminal.

mkdir -p ~/practice/vars && cd ~/practice/vars

Assigning variables: no spaces around =

An assignment is a name, an equals sign and a value, with nothing in between:

name=sid
echo "$name"
sid

Spaces change the meaning completely, because Bash splits a command line into words on spaces before it decides what anything means. Each of these is a different mistake:

name = sid
name =sid
name= sid
greeting=Hello world
bash: name: command not found
bash: name: command not found
bash: sid: command not found
bash: world: command not found
  • name = sid and name =sid run a command called name with arguments.
  • name= sid is valid syntax for something else: run the command sid with name set to an empty string in its environment. We'll use that form on purpose later.
  • greeting=Hello world assigns Hello and then tries to run world. A value with spaces needs quotes: greeting="Hello world".

Names may contain letters, digits and underscores, and cannot start with a digit. Anything else makes Bash treat the whole word as a command:

2fast=yes
backup-dir=/srv/backups
backup_dir=/srv/backups
echo "$backup_dir"
bash: 2fast=yes: command not found
bash: backup-dir=/srv/backups: No such file or directory
/srv/backups

The second error is different because the word contains a /, so Bash tried to run it as a file path. The convention I follow, and that most style guides recommend: lower-case names for variables inside your own scripts, upper-case for environment variables and constants (PATH, DB_HOST). That keeps you from accidentally overwriting something like PATH or USER.

Reading variables: $name and ${name}

$name and ${name} mean the same thing. The braces are needed when the name is followed by characters that could be part of a name:

service=nginx
echo "Restarting $service..."
echo "$service_log"
echo "${service}_log"
echo "[$no_such_variable]"
Restarting nginx...
 
nginx_log
[]

$service_log asked for a variable called service_log, which doesn't exist, so it expanded to nothing. Bash does not complain about unset variables by default; it silently substitutes an empty string. That is why a typo in a variable name can turn rm -rf "$build_dir/" into rm -rf /. Error Handling, Traps, and Debugging shows set -u, which turns this into an error.

Quoting: single, double, and $'...'

Quoting controls which expansions happen inside a piece of text.

Single quotes make everything literal. No variables, no command substitution, no escapes:

user=sid
echo 'Hello $user, it is $(date +%A)'
Hello $user, it is $(date +%A)

Double quotes allow $ expansions (variables, $(...) command substitution, $((...)) arithmetic) but switch off word splitting and globbing. A backslash escapes $, backtick, " and \ itself:

echo "Hello $user, you have $((3 * 4)) new messages"
echo "Cost: \$5, path: C:\\temp, quote: \"ok\""
Hello sid, you have 12 new messages
Cost: $5, path: C:\temp, quote: "ok"

A single quote can't appear inside single quotes, even with a backslash. You can end the quoted part, add an escaped quote, and start again, or just use double quotes:

echo 'It'\''s fine'
echo "It's fine"
It's fine
It's fine

ANSI-C quoting, $'...', interprets backslash escapes such as \t, \n and \'. It is the clean way to put a tab or newline into a value:

echo $'It\'s fine'
printf '%s\n' $'name\tport' $'line one\nline two'
It's fine
name    port
line one
line two
Quoting$var and $(cmd)Globbing and word splittingBackslash escapes
noneexpandedyes\ escapes the next character
"..."expandednoonly before $, backtick, ", \
'...'literalnonone
$'...'literalnoC-style: \n, \t, \', \\

The ! inside double quotes

At an interactive prompt, ! triggers history expansion, even inside double quotes:

echo "Build passed!"
echo "Error!Retry"
echo 'Error!Retry'
Build passed!
bash: !Retry: event not found
Error!Retry

A ! at the end of a string or before a space is left alone, which is why the first line worked. Inside a word, Bash looked for a previous command starting with Retry. Use single quotes for text containing !. Scripts don't have history expansion, so this only bites at the prompt.

The unquoted variable bug

When you use a variable without double quotes, Bash runs two more steps on its value: word splitting (breaking it apart on spaces, tabs and newlines) and pathname expansion (treating *, ? and [ as glob characters). Neither is what you want 99% of the time. Here is the classic failure, with a file name containing a space:

printf 'id,total\n1,9.99\n2,24.50\n' > 'Q3 sales.csv'
file='Q3 sales.csv'
wc -l $file
wc -l "$file"
wc: Q3: No such file or directory
wc: sales.csv: No such file or directory
0 total
3 Q3 sales.csv

printf '[%s]\n' prints each argument it receives in brackets, which makes word splitting visible:

printf '[%s]\n' $file
printf '[%s]\n' "$file"
[Q3]
[sales.csv]
[Q3 sales.csv]

The glob half of the problem is sneakier. A message that contains * turns into a directory listing:

msg='Warning: * matches everything'
echo $msg
echo "$msg"
Warning: Q3 sales.csv matches everything
Warning: * matches everything

Word splitting also collapses runs of whitespace, which mangles aligned text:

line='web01    10.0.0.5    running'
echo $line
echo "$line"
web01 10.0.0.5 running
web01    10.0.0.5    running

And an empty unquoted variable disappears entirely, which breaks tests and cd:

answer=
[ $answer = yes ] && echo confirmed
[ "$answer" = yes ] || echo "not confirmed"
dir='Q3 reports'
mkdir "$dir"
cd $dir
bash: [: =: unary operator expected
not confirmed
bash: cd: too many arguments

With $answer empty, the test became [ = yes ], which is malformed. The rule that follows from all of this is simple: put double quotes around every variable expansion, "$var", unless you can say exactly why you need splitting or globbing. ShellCheck, a linter covered in Writing Production-Ready Scripts, flags unquoted variables for exactly this reason.

IFS: what word splitting splits on

Word splitting uses the characters in the IFS variable (Internal Field Separator). Its default is space, tab and newline, which printf %q shows in $'...' form:

printf '%q\n' "$IFS"
$' \t\n'

You rarely change IFS globally. The common, safe use is setting it for a single read command, to split a line on a different character. read and the <<< here-string are covered in Loops, Functions, and Reading Input; the point here is that IFS=, before the command applies to that command only:

row='web01,10.0.0.5,running'
IFS=, read -r host ip state <<< "$row"
echo "host=$host ip=$ip state=$state"
printf '%q\n' "$IFS"
host=web01 ip=10.0.0.5 state=running
$' \t\n'

Parameter expansion

Inside ${...}, Bash can do far more than read a value. These operations are built into the shell, so they are fast and need no external commands like sed or basename.

Defaults and required values

unset DB_HOST
echo "${DB_HOST:-localhost}"
echo "DB_HOST is now: [$DB_HOST]"
echo "${DB_HOST:=localhost}"
echo "DB_HOST is now: [$DB_HOST]"
localhost
DB_HOST is now: []
localhost
DB_HOST is now: [localhost]

:- substitutes a default without changing the variable. := substitutes it and assigns it. The colon means "unset or empty"; without the colon, only "unset" counts:

DB_PORT=
echo "[${DB_PORT:-5432}] [${DB_PORT-5432}]"
[5432] []

:? stops with an error message when a value is missing. At the prompt it just fails the command:

echo "${API_TOKEN:?must be set}"
echo "exit status: $?"
bash: API_TOKEN: must be set
exit status: 1

In a script it is much more useful, because the script stops right there instead of carrying on with an empty value. The : command does nothing, which makes it a convenient place to put the check:

#!/usr/bin/env bash
echo "Deploying..."
: "${API_TOKEN:?API_TOKEN must be set}"
echo "Calling the API with a token of ${#API_TOKEN} characters"
bash deploy.sh
echo "exit status: $?"
API_TOKEN=s3cr3t-t0ken bash deploy.sh
Deploying...
deploy.sh: line 3: API_TOKEN: API_TOKEN must be set
exit status: 1
Deploying...
Calling the API with a token of 12 characters

:+ is the opposite of :-: it gives the alternative only when the variable is set. It is good for optional flags:

debug=1
echo "flags: ${debug:+--debug}"
unset debug
echo "flags: ${debug:+--debug}"
flags: --debug
flags: 

And ${var+set} (no colon) is the reliable way to tell "unset" apart from "set to an empty string":

unset maybe; empty=
echo "maybe:[${maybe+set}] empty:[${empty+set}]"
maybe:[] empty:[set]

Length, and trimming prefixes and suffixes

${#var} is the length in characters. # and % remove a pattern from the start or end of the value; doubling them makes the match as long as possible. The patterns are the same glob patterns from the previous article.

release=v2.14.0
echo "${#release}"
path=/var/log/nginx/access.log.2.gz
echo "${path##*/}"
echo "${path%/*}"
7
access.log.2.gz
/var/log/nginx

${path##*/} removes the longest prefix ending in /, leaving the file name (like basename). ${path%/*} removes the shortest suffix starting with /, leaving the directory (like dirname). The difference between single and double operators shows up with multi-part extensions:

file=backup-2026-11-09.tar.gz
echo "${file%.gz}"
echo "${file%.*}"
echo "${file%%.*}"
echo "${file#*.}"
echo "${file##*.}"
backup-2026-11-09.tar
backup-2026-11-09.tar
backup-2026-11-09
tar.gz
gz

A way to remember which is which: on a US keyboard # is to the left of $ and % is to the right, so # trims the left end and % trims the right end.

Search and replace

${var/pattern/replacement} replaces the first match, ${var//pattern/replacement} replaces all of them. /# anchors the match to the start and /% to the end:

title='Q3 sales report final.csv'
echo "${title/ /_}"
echo "${title// /_}"
echo "${title//[[:space:]]/}"
url=http://api.example.com/v1/orders
echo "${url/#http:/https:}"
echo "${file/%.tar.gz/.zip}"
Q3_sales report final.csv
Q3_sales_report_final.csv
Q3salesreportfinal.csv
https://api.example.com/v1/orders
backup-2026-11-09.zip

Substrings and case

${var:offset:length} extracts part of a value. A negative offset counts from the end, but it needs a space (or parentheses) after the colon, otherwise it is read as the :- default operator:

stamp=20261109T2314
echo "${stamp:0:4}-${stamp:4:2}-${stamp:6:2}"
echo "${stamp: -4}"
echo "${stamp:-4}"
2026-11-09
2314
20261109T2314

The last line is the trap: ${stamp:-4} means "stamp, or 4 if it's empty", so it printed the whole value.

Bash 4 and later can change case: ^ upper-cases the first character, ^^ all of them, and , and ,, do the same for lower case:

env_name=production
echo "${env_name^}" "${env_name^^}"
answer=YES
echo "${answer,,}"
Production PRODUCTION
yes

Reference table

ExpansionResult
${var:-word}word if var is unset or empty, otherwise $var
${var:=word}same, and also assigns word to var
${var:?message}error with message if unset or empty (exits a script)
${var:+word}word if var is set and non-empty, otherwise nothing
${#var}length of the value
${var#pat} / ${var##pat}remove shortest / longest match of pat from the start
${var%pat} / ${var%%pat}remove shortest / longest match of pat from the end
${var/pat/rep} / ${var//pat/rep}replace first / every match
${var/#pat/rep} / ${var/%pat/rep}replace a match at the start / end
${var:off:len} / ${var: -n}substring / last n characters
${var^} ${var^^} ${var,} ${var,,}change case of the first / all characters

Drop the colon from the first four (${var-word} and so on) and they test only for "unset", treating an empty value as set. The full list is in the Shell Parameter Expansion section of the Bash manual.

readonly, unset and declare -p

readonly turns a variable into a constant for the rest of the shell session or script. Any attempt to change or remove it fails:

readonly APP_ENV=production
APP_ENV=staging
unset APP_ENV
declare -p APP_ENV
bash: APP_ENV: readonly variable
bash: unset: APP_ENV: cannot unset: readonly variable
declare -r APP_ENV="production"

declare -p shows a variable together with its attributes: -r for read-only, -x for exported, -- for none. unset removes a variable completely, which is different from setting it to an empty string:

tmp_dir=/srv/tmp
declare -p tmp_dir
unset tmp_dir
declare -p tmp_dir
declare -- tmp_dir="/srv/tmp"
bash: declare: tmp_dir: not found

In scripts, readonly is a good fit for values that are computed once at the top and must not change, such as a script's own directory or a release version.

Shell variables and environment variables

Every variable you have created so far is a shell variable: it exists only inside the current shell. Programs you start from that shell (child processes) don't see it. To pass a variable to children, you export it, which puts it in the environment:

color=blue
bash -c 'echo "child sees: [$color]"'
export color
bash -c 'echo "child sees: [$color]"'
declare -p color
export -n color
bash -c 'echo "child sees: [$color]"'
child sees: []
child sees: [blue]
declare -x color="blue"
child sees: []

bash -c '...' starts a new shell process, so it is a convenient stand-in for any program: Python, Node, a database client, terraform. export -n removes the export flag but keeps the variable. Most of the time you export at the moment of assignment, export LOG_LEVEL=debug.

Setting a variable for one command

Put assignments in front of a command and they go into that command's environment only. Your shell is unchanged:

TZ=UTC date +%H:%M
TZ=Asia/Tokyo date +%H:%M
GREETING=hi bash -c 'echo "child: $GREETING"'
echo "parent: [$GREETING]"
02:46
11:46
child: hi
parent: []

This is the cleanest way to configure a single run, for example API_TOKEN=... bash deploy.sh above, or DEBUG=1 ./run-tests.sh.

A child can never change its parent

The environment is copied down to children when they start. Nothing flows back up. A script that exports a variable affects only itself and its own children:

printf '%s\n' 'export DEPLOY_ENV=staging' 'echo "inside script: $DEPLOY_ENV"' > set-env.sh
bash set-env.sh
echo "after bash: [$DEPLOY_ENV]"
source set-env.sh
echo "after source: [$DEPLOY_ENV]"
inside script: staging
after bash: []
inside script: staging
after source: [staging]

source (also written .) is different: it runs the file's commands in your current shell instead of a child, so its assignments stick. That's how ~/.bashrc and Python's venv/bin/activate change your session.

Looking at the environment: env, printenv, set

printenv NAME prints environment variables and fails (exit status 1) for names that aren't exported. env with no arguments prints the whole environment, and set prints all shell variables (exported or not) plus functions, which is why it is much longer:

printenv HOME USER SHELL
printenv color
echo "status: $?"
set | wc -l
env | wc -l
/home/sid
sid
/bin/bash
status: 1
48
16

Your numbers will be higher; a desktop session typically has dozens of environment variables. env can also run a command with a modified environment. env -i starts with an empty one, which is a good way to test whether a script depends on variables it doesn't set itself:

env -i bash -c 'echo "HOME=[$HOME] USER=[$USER]"; echo "PATH=$PATH"'
env -i FOO=bar env
HOME=[] USER=[]
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FOO=bar

Notice that the child Bash still had a PATH: when none is inherited, Bash falls back to a built-in default. cron jobs run with a similarly sparse environment, which is the root cause of many "works in my terminal, fails in cron" problems (System Monitoring and Scheduling with cron and systemd has the details).

Variables you'll use all the time

VariableMeaningExample value
HOMEyour home directory; ~ expands to it/home/sid
USERyour user namesid
SHELLyour login shell (not necessarily the one running)/bin/bash
PWD / OLDPWDcurrent and previous directory (cd - uses OLDPWD)/home/sid/practice/vars
PATHdirectories searched for commandssee below
IFSword-splitting charactersspace, tab, newline
EDITOR / VISUALeditor that git, crontab -e and others openvim
LANG / LC_*language and formatting localeC.UTF-8
TZtime zone overrideUTC
BASH_VERSIONversion of the running Bash5.2.21(1)-release
echo "$HOME | $USER | $SHELL"
cd /etc
echo "PWD=$PWD OLDPWD=$OLDPWD"
cd -
echo "$BASH_VERSION"
/home/sid | sid | /bin/bash
PWD=/etc OLDPWD=/home/sid/practice/vars
/home/sid/practice/vars
5.2.21(1)-release

PATH: how Bash finds commands

When you type a command name without a /, Bash first checks whether it is an alias, a function or a builtin. If not, it searches the directories listed in PATH, left to right, and runs the first match. Here is the default PATH on Ubuntu 24.04, one directory per line:

echo "$PATH"
echo "$PATH" | tr ':' '\n'
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
/usr/games
/usr/local/games
/snap/bin

(The | sends the output of echo into tr, which swaps colons for newlines; pipes are the subject of the next article.) If you use WSL, your real PATH will also contain many /mnt/c/... directories, because WSL appends the Windows PATH by default.

type tells you what a name resolves to. type -a lists every match in order, and type -P prints only the file path:

type -a bash
type cd
type -P date
bash is /usr/bin/bash
bash is /bin/bash
cd is a shell builtin
/usr/bin/date

(bash appears twice because on modern Ubuntu /bin is a symbolic link to /usr/bin.) Finding Files with find, locate, and xargs compares type, which and command -v in more detail.

Adding your own directory to PATH

Let's make a small tool and put it on the PATH:

mkdir -p ~/bin
printf '%s\n' '#!/usr/bin/env bash' 'echo "Disk usage for $HOME:"' 'du -sh "$HOME"' > ~/bin/diskcheck
chmod +x ~/bin/diskcheck
diskcheck
PATH="$HOME/bin:$PATH"
diskcheck
type diskcheck
bash: diskcheck: command not found
Disk usage for /home/sid:
24K     /home/sid
diskcheck is hashed (/home/sid/bin/diskcheck)

(chmod +x makes the file executable; File Permissions and Ownership explains it.) Three details in that PATH= line matter:

  • Keep $PATH in the new value. PATH="$HOME/bin:$PATH" adds one directory; PATH="$HOME/bin" replaces everything. See the common mistakes below.
  • Prepend or append on purpose. Putting your directory first lets your tools override system commands of the same name. Appending (PATH="$PATH:$HOME/bin") means system commands always win.
  • Never add . (the current directory). With . in PATH, running ls inside a directory someone else controls could run their ls.

"Hashed" in the type output refers to a cache: after Bash finds a command once, it remembers the full path instead of searching again. That cache can go stale. Watch what happens when a file in ~/bin shadows a system command and is then deleted:

printf '%s\n' '#!/usr/bin/env bash' 'echo "this is not the real ls"' > ~/bin/ls
chmod +x ~/bin/ls
type -a ls
ls ~/bin
rm ~/bin/ls
ls ~/bin
hash -r
ls ~/bin
ls is /home/sid/bin/ls
ls is /usr/bin/ls
ls is /bin/ls
this is not the real ls
bash: /home/sid/bin/ls: No such file or directory
diskcheck

After the rm, Bash still tried the remembered path. hash -r clears the cache (running hash alone shows it). You'll hit this after installing a newer version of a tool into a different directory: the old one keeps running in shells that already used it.

A PATH helper that doesn't create duplicates

If ~/.bashrc does PATH="$HOME/bin:$PATH" and you source it several times, the directory piles up. This function only adds a directory that isn't already there. It uses [[ ... ]] pattern matching, which Your First Scripts covers properly:

path_prepend() {
  if [[ ":$PATH:" != *":$1:"* ]]; then
    PATH="$1:$PATH"
  fi
}
path_prepend "$HOME/bin"
path_prepend "$HOME/bin"
echo "$PATH"
/home/sid/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Wrapping both sides in colons means /home/sid/bin is matched as a whole entry, so it won't be confused with /home/sid/bin2.

Making settings permanent with ~/.bashrc

Everything above disappears when the shell exits. To keep it, put it in a startup file. On Ubuntu, two files matter:

  • ~/.bashrc is read by every interactive shell that isn't a login shell: each new terminal tab, and bash typed at a prompt.
  • ~/.profile is read by login shells (SSH sessions, console logins). Ubuntu's default ~/.profile sources ~/.bashrc, and it already adds ~/bin and ~/.local/bin to PATH if those directories exist when you log in.

Here I append two settings to a copy of Ubuntu's default ~/.bashrc and load it into the current shell:

printf '%s\n' '' '# personal settings' 'export EDITOR=vim' 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
tail -n 3 ~/.bashrc
echo "[$EDITOR]"
source ~/.bashrc
echo "[$EDITOR]"
# personal settings
export EDITOR=vim
export PATH="$HOME/bin:$PATH"
[]
[vim]

(Sourcing Ubuntu's .bashrc also sets a coloured prompt, so don't be surprised when yours changes.) One detail trips people up: Ubuntu's .bashrc starts with a check that returns immediately in non-interactive shells. So a fresh script does not pick up these settings unless it inherited them from an interactive shell that exported them:

bash -c 'echo "non-interactive child: [$EDITOR]"'
env -u EDITOR bash -c 'echo "fresh non-interactive shell: [$EDITOR]"'
env -u EDITOR bash -i -c 'echo "fresh interactive shell: [$EDITOR]"' 2>/dev/null
non-interactive child: [vim]
fresh non-interactive shell: []
fresh interactive shell: [vim]

env -u EDITOR removes the variable before starting the child, simulating a shell that wasn't started from your terminal. The practical rule: scripts that run from cron, systemd or CI should set or receive every variable they need explicitly, and never rely on ~/.bashrc.

Loading settings from a .env file

Applications commonly keep configuration in a .env file of NAME=value lines. Docker Compose, many web frameworks and plenty of deploy scripts read this format:

printf '%s\n' '# billing service settings' 'DB_HOST=db.internal' 'DB_PORT=5432' 'APP_NAME="Billing API"' > app.env
cat app.env
# billing service settings
DB_HOST=db.internal
DB_PORT=5432
APP_NAME="Billing API"

Because the lines are valid Bash assignments, source can read them, but that creates shell variables, not environment variables, so a program you start next won't see them. set -a (allexport) marks every variable assigned while it is on for export:

source app.env
bash -c 'echo "child sees: [$APP_NAME] [$DB_HOST]"'
unset DB_HOST DB_PORT APP_NAME
set -a
source app.env
set +a
bash -c 'echo "child sees: [$APP_NAME] [$DB_HOST:$DB_PORT]"'
child sees: [] []
child sees: [Billing API] [db.internal:5432]

To load the settings for a single program without leaving them in your shell, do it inside a subshell, ( ... ), which is a child copy of your shell that disappears afterwards:

unset DB_HOST DB_PORT APP_NAME
( set -a; source app.env; bash -c 'echo "in subshell: $APP_NAME"' )
echo "after: [$APP_NAME]"
in subshell: Billing API
after: []

Sourcing runs code

source executes the file as Bash. A line such as NAME=$(some-command) in a .env file runs that command. Only source .env files you control, and keep them out of version control if they contain secrets: they belong in a .gitignore and should have 600 permissions, as described in File Permissions and Ownership.

Where you'll use this

Configurable scripts. Almost every useful script reads its settings from variables with defaults, so the same file works on a laptop, a staging server and in CI. Save this as backup-db.sh:

#!/usr/bin/env bash
# backup-db.sh - work out where tonight's database dump should go
db_name=${1:?usage: backup-db.sh DATABASE}
backup_dir=${BACKUP_DIR:-$HOME/backups}
keep_days=${KEEP_DAYS:-14}
stamp=$(date +%F)
outfile="$backup_dir/${db_name}-${stamp}.sql.gz"
 
echo "database : $db_name"
echo "target   : $outfile"
echo "file name: ${outfile##*/}"
echo "retention: $keep_days days"
echo "host tag : ${HOSTNAME_TAG:-unknown}"

$1 is the script's first argument (Your First Scripts covers arguments). Run it three ways:

bash backup-db.sh
echo "exit status: $?"
bash backup-db.sh billing
BACKUP_DIR=/srv/backups KEEP_DAYS=30 HOSTNAME_TAG=db01 bash backup-db.sh billing
backup-db.sh: line 3: 1: usage: backup-db.sh DATABASE
exit status: 1
database : billing
target   : /home/sid/backups/billing-2026-11-09.sql.gz
file name: billing-2026-11-09.sql.gz
retention: 14 days
host tag : unknown
database : billing
target   : /srv/backups/billing-2026-11-09.sql.gz
file name: billing-2026-11-09.sql.gz
retention: 30 days
host tag : db01

Without an argument, :? stops the script with a usage message before it does anything. With one, sensible defaults apply. A cron job or CI pipeline can override any default from the environment without editing the file. The real dump command is added in Real-World Scripts: Backups, Log Reports, and Cleanup.

Other places this shows up:

  • CI/CD pipelines. Jenkins, GitHub Actions and GitLab inject build numbers, branch names and secrets as environment variables. Your build scripts read them as "${BUILD_NUMBER:-local}". Jenkins credentials arrive the same way.
  • Containers. docker run -e DB_HOST=... and Kubernetes env: entries set environment variables; the program inside reads them exactly like bash -c did above.
  • Tool configuration. EDITOR, PAGER, LANG, TZ, http_proxy and KUBECONFIG change how other programs behave, and TF_VAR_name sets Terraform variables.
  • File-name surgery. ${f%.csv}.json, ${path##*/} and ${name// /_} rename and convert files in loops without calling basename or sed for every file.

Common mistakes

Loading a .env file with export $(cat .env | xargs)

This one-liner is copied around a lot. It breaks on comments and on quoted values with spaces:

export $(cat app.env | xargs)
echo "APP_NAME=[$APP_NAME]"
declare -p API
bash: export: `#': not a valid identifier
APP_NAME=[Billing]
declare -x API

The comment's # caused an error, and its other words (billing, service, settings) were quietly exported as empty variables. Worse, the unquoted $(...) was word-split, so APP_NAME got only Billing, and a stray variable named API appeared. Use set -a; source file; set +a instead.

Overwriting PATH instead of extending it

PATH=~/bin
ls
diskcheck
bash: ls: command not found
/usr/bin/env: ‘bash’: No such file or directory

Every system directory is gone, so nothing outside ~/bin can be found, and even diskcheck fails because its #!/usr/bin/env bash line searches PATH for bash. Commands still work by full path (/usr/bin/ls). To recover, close the terminal and open a new one, or set PATH back to the default list shown earlier. If the mistake is in ~/.bashrc, every new terminal will be broken the same way, so fix the file using full paths: /usr/bin/vim ~/.bashrc.

On a stock Ubuntu terminal, the command-not-found helper loaded by /etc/bash.bashrc makes the error more helpful. This is what I got from ls with a broken PATH in a normal interactive shell:

Command 'ls' is available in the following places
 * /bin/ls
 * /usr/bin/ls
The command could not be located because '/usr/bin:/bin' is not included in the PATH environment variable.
ls: command not found

Unquoted variables with spaces or empty values

The errors from earlier, collected, because you will see them in other people's scripts:

wc: Q3: No such file or directory
bash: [: =: unary operator expected
bash: cd: too many arguments

All three disappear with double quotes: wc -l "$file", [ "$answer" = yes ], cd "$dir".

Expecting a script to change your shell

bash set-env.sh runs in a child process, and its export dies with it. If a file is meant to modify your current session (activate an environment, set variables), it must be sourced: source set-env.sh.

Summary

  • Assignments are name=value with no spaces; quote values that contain spaces. Names use letters, digits and _ and can't start with a digit.
  • Single quotes are fully literal, double quotes allow $ expansions only, and $'...' interprets escapes like \n and \t.
  • Unquoted expansions are word-split on IFS and then globbed. Quote every expansion, "$var", unless you need splitting.
  • ${var:-default}, ${var:=default}, ${var:?message} and ${var:+alt} handle missing values; without the colon only "unset" counts as missing.
  • #/## trim from the start, %/%% from the end, / and // replace, ${var:off:len} extracts, ^^ and ,, change case. ${#var} is the length.
  • Shell variables stay in the current shell. export puts them in the environment of child processes; VAR=value cmd sets one for a single command; children can never change the parent, which is why config files are sourced.
  • Bash searches PATH left to right and caches what it finds (hash -r clears it). Extend it with PATH="$dir:$PATH", never replace it, and never add ..
  • Interactive settings go in ~/.bashrc (login shells read ~/.profile); scripts for cron and CI must not depend on them. Load .env files with set -a; source file; set +a.

Exercises

Run these in ~/practice/vars.

Exercise 1: Fix the assignmentseasy

Each of these lines is meant to create one variable, and each one fails. Fix them, then print all three in one sentence: Order Service logs in /var/log/myapp (rotate at 50M).

log-dir=/var/log/myapp
max_size = 50M
app_name=Order Service
Show Solution
log_dir=/var/log/myapp
max_size=50M
app_name="Order Service"
echo "$app_name logs in $log_dir (rotate at $max_size)"
Order Service logs in /var/log/myapp (rotate at 50M)

- isn't allowed in a name, spaces around = turn the line into a command, and a value with a space needs quotes (otherwise Service runs as a command with app_name=Order in its environment).

Exercise 2: Take a path aparteasy

Given f=/var/log/nginx/access.log.3.gz, use only parameter expansion to print the directory (/var/log/nginx), the file name (access.log.3.gz), and the rotation number (3).

Hint

The rotation number needs two steps: remove everything up to .log., then remove .gz.

Show Solution
f=/var/log/nginx/access.log.3.gz
echo "${f%/*}"
echo "${f##*/}"
n=${f##*.log.}
echo "${n%.gz}"
/var/log/nginx
access.log.3.gz
3

%/* removes the shortest suffix starting with /, ##*/ removes the longest prefix ending with /, and ##*.log. removes everything up to and including the last .log..

Exercise 3: A connection string with defaultsmedium

Write connect.sh that prints a PostgreSQL URL of the form postgresql://USER@HOST:PORT/NAME. DB_USER, DB_HOST and DB_PORT default to app, localhost and 5432. DB_NAME is required: if it's missing, the script must stop with the message DB_NAME is required. Test it with no variables, with only DB_NAME=billing, and with DB_NAME, DB_HOST and DB_USER set.

Show Solution
#!/usr/bin/env bash
db_name=${DB_NAME:?DB_NAME is required}
echo "postgresql://${DB_USER:-app}@${DB_HOST:-localhost}:${DB_PORT:-5432}/$db_name"
bash connect.sh
DB_NAME=billing bash connect.sh
DB_NAME=billing DB_HOST=db.internal DB_USER=report bash connect.sh
connect.sh: line 2: DB_NAME: DB_NAME is required
postgresql://app@localhost:5432/billing
postgresql://report@db.internal:5432/billing

The variables set in front of bash connect.sh exist only in that one script's environment, so each run is independent, and nothing is left behind in your shell.

Exercise 4: Slugify a report titlemedium

Turn t='Q3 Sales Report FINAL' into the file name q3-sales-report-final.csv using only parameter expansion (no tr, no sed).

Show Solution
t='Q3 Sales Report FINAL'
slug=${t,,}
slug=${slug// /-}
echo "$slug.csv"
q3-sales-report-final.csv

,, lower-cases every character and // /- replaces every space with a hyphen. Bash can't nest these two operations in a single ${...}, so an intermediate variable is the normal way to chain them.

Exercise 5: Load settings for one command onlyhard

Using app.env from the .env section, run bash -c 'echo "$APP_NAME on $DB_HOST:$DB_PORT"' so that it prints Billing API on db.internal:5432, but afterwards none of the three variables exists in your shell. Do not edit app.env.

Hint

You need set -a, source, and a way to make all of it temporary.

Show Solution
unset DB_HOST DB_PORT APP_NAME
( set -a; source app.env; bash -c 'echo "$APP_NAME on $DB_HOST:$DB_PORT"' )
declare -p APP_NAME DB_HOST DB_PORT
Billing API on db.internal:5432
bash: declare: APP_NAME: not found
bash: declare: DB_HOST: not found
bash: declare: DB_PORT: not found

source alone would create unexported shell variables, so the child would print nothing useful. set -a exports everything assigned while it's active. The parentheses run all of it in a subshell, a temporary copy of your shell, so the variables vanish when it exits.


Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026. Every command was run as shown in an interactive shell started without startup files and with PATH set to Ubuntu's default from /etc/environment (WSL normally appends Windows directories to it), with a fresh, empty home directory so that ~/bin and ~/.bashrc started out empty. The .bashrc section used a copy of Ubuntu's stock /etc/skel/.bashrc; the command-not-found output came from a normal interactive shell with Ubuntu's default startup files. Times in the TZ example are from the moment I ran it.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.