On this page
- How do I create and read a variable?
- When do I need double quotes, single quotes or none?
- How do I store the output of a command?
- How do I set defaults and require values?
- How do I cut, replace and change case in strings?
- How do I do arithmetic?
- What is the difference between a shell variable and an exported one?
- How do I keep variables safe inside functions and scripts?
- Questions
How do I create and read a variable?
Write the name, an equals sign and the value with no spaces anywhere, then put a dollar sign in front of the name to use it. Names may contain letters, digits and underscores and must not start with a digit:
site="example.net"
port=8080
echo "Serving $site on port $port"
echo "Next port is ${port}1"The line site = "example.net" with spaces fails, because Bash reads site as a command name with two arguments. Braces around the name, as in ${port}1, mark where the name ends when letters or digits follow directly. A convention worth keeping: lowercase names for your own variables, uppercase for environment variables such as PATH or HOME, so you never overwrite a system value by accident. Bash variables are untyped strings; they only behave as numbers inside arithmetic.
When do I need double quotes, single quotes or none?
Use double quotes around nearly every expansion. Unquoted, the value is split on spaces and glob characters like * are expanded to file names, which breaks paths with spaces and can even delete the wrong files:
dir="/srv/my backups"
ls $dir # wrong: two arguments, /srv/my and backups
ls "$dir" # right: one argumentSingle quotes keep everything literal; no dollar sign or backslash is interpreted. Double quotes still allow $var, $(command) and $((math)) inside. When you need an escape sequence such as a tab or newline, the $'...' form interprets it:
echo 'Cost: $5'
echo "User: $USER"
printf '%s\n' $'col1\tcol2'For printing anything that might begin with a dash or contain backslashes, printf '%s\n' "$value" is safer than echo, whose options differ between shells.
How do I store the output of a command?
Wrap the command in $( ) and assign the result. Trailing newlines are removed automatically:
kernel="$(uname -r)"
free_mb="$(free -m | awk '/^Mem:/ {print $7}')"
ip4="$(ip -4 -o addr show scope global | awk '{print $4}' | cut -d/ -f1 | head -n 1)"
echo "Kernel $kernel, $free_mb MB available, address $ip4"On a fresh server the last line prints your public address, for example 198.51.100.24. Prefer $( ) over the older backtick form because it nests cleanly and reads better. The exit status of the inner command is available as $? right after the assignment, which lets you test whether the command worked.
How do I set defaults and require values?
Parameter expansion has operators for empty or missing variables, which saves a lot of if blocks:
${host:-localhost}: use localhost if host is unset or empty.${host:=localhost}: same, and also assign it.${host:?host is required}: stop the script with that message if empty.${debug:+--verbose}: produce --verbose only when debug has a value.
#!/usr/bin/env bash
target="${1:-/var/www}"
keep_days="${KEEP_DAYS:-14}"
: "${DB_PASS:?set DB_PASS before running}"
echo "Cleaning $target, keeping $keep_days days"The colon command : does nothing except evaluate its arguments, which makes it a neat way to trigger the check. Callers can now override the default with KEEP_DAYS=30 ./clean.sh /srv/app.
How do I cut, replace and change case in strings?
Bash can edit text inside a variable directly, which is faster than piping through sed for small jobs:
path="/var/log/nginx/access.log.1"
echo "${#path}" # length: 27
echo "${path##*/}" # access.log.1 (like basename)
echo "${path%/*}" # /var/log/nginx (like dirname)
echo "${path%.1}" # strip a suffix
echo "${path/nginx/caddy}" # replace first match
echo "${path//\//:}" # replace every slash with a colon
echo "${path:9:5}" # substring from offset 9, 5 characters: nginx
user="Deploy"
echo "${user,,} ${user^^}" # deploy DEPLOYThe memory aid: # cuts from the front, % from the back; doubling the symbol makes the match as long as possible. Patterns use glob syntax, not regular expressions. For regex work, see the =~ test in if, else and case in Bash.
How do I do arithmetic?
Put integer expressions inside $(( )). Variables inside do not need a dollar sign:
used=37; total_gb=80
pct=$(( used * 100 / total_gb ))
echo "Disk ${pct}% used"
(( count += 1 ))
(( pct > 90 )) && echo "almost full"Bash only does whole numbers, so 37 divided by 80 gives 0; multiply first, as above. For decimals, hand the work to awk or bc: awk "BEGIN {printf \"%.2f\n\", 37/80}". Watch out for numbers with leading zeros such as 08, which Bash reads as octal and rejects; write $(( 10#$month )) to force base ten.
What is the difference between a shell variable and an exported one?
A plain variable lives only in the current shell; export copies it into the environment of every program that shell starts. Test it yourself:
color=blue
bash -c 'echo "child sees: $color"'
export color
bash -c 'echo "child sees: $color"'The first child prints nothing after the colon, the second prints blue. Export only what other programs actually read, such as EDITOR or an app setting. To pass a value to one command without exporting it, prefix the command: TZ=UTC date. Making variables permanent for every login is covered in environment variables on Linux.
How do I keep variables safe inside functions and scripts?
Declare helper variables with local inside functions so they do not leak into the rest of the script, and mark constants with readonly so a later typo cannot overwrite them:
readonly CONF_DIR="/etc/myapp"
tidy_name() {
local raw="$1"
local clean="${raw// /_}"
printf '%s\n' "${clean,,}"
}
tidy_name "Monthly Report" # monthly_report
declare -p CONF_DIRdeclare -p shows a variable with its attributes, handy when debugging. Avoid naming variables after environment values you rely on, such as PATH, USER or HOME; overwriting PATH by accident makes every following command fail with not found. More on scoping in Functions in Bash.
Questions about Bash variables and strings
Why is my variable empty after a pipe into while read?
Each part of a pipeline runs in a subshell, so values set inside the loop vanish afterwards. Feed the loop with done < file or done < <(command) instead, or set shopt -s lastpipe in a script.
Should I use curly braces every time?
Only when needed: before letters or digits that follow the name, for parameter expansion, and for positional parameters above 9 such as ${10}. Quotes matter far more than braces.
How do I check whether a variable is set at all?
Use [[ -v varname ]], which is true even when the value is empty. [[ -n "$varname" ]] tests for a non-empty value instead.
Can Bash handle decimal numbers?
Not natively. Integer math works in $(( )); for decimals use awk or bc -l and keep the result as a string.
Where do I keep passwords that scripts need?
Not in the script itself. Store them in a file readable only by the service user (mode 600) and load it with source, or pass them through a systemd EnvironmentFile.