bhylu.com

Advertisements

Bash Quoting

Keep a filename with spaces as one argument.

How it works

Quoting controls which expansions Bash performs and how many arguments a command receives. Double quotes allow variable expansion while preserving the expanded value as one argument. Single quotes preserve literal characters. Unquoted expansion can introduce word splitting and pathname expansion, so a harmless-looking variable can turn into several filenames or options.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

quoting.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
name="north map.txt"
set -- "$name"
[[ $# -eq 1 && $1 == "north map.txt" ]] || exit 1
printf "%s\n" "$1"
printf "%s\n" '$name stays literal'

Expected result

north map.txt
$name stays literal

The positional-parameter count makes the argument boundary observable. The second printf shows that single quotes do not expand the variable. Quoting is not a cosmetic convention: it defines how the called program receives data. Later file examples also use -- to separate options from filenames where supported.

Primary technical reference: Bash documentation.