Variables
| Since: | POSIX(sh互換) |
|---|
In shell scripts, you can use variables to store and reuse values. The syntax for assignment, reference, and deletion differs slightly from other programming languages, so it is important to understand each rule carefully.
Assigning Variables
When assigning a value to a variable, do not put spaces around =. Adding spaces causes the shell to interpret the expression as a command and its arguments, resulting in an error.
| Syntax | Description |
|---|---|
var=value | Assigns value to the variable var. No spaces are allowed around = (spaces cause an error). |
var="hello world" | Enclose values that contain spaces in double quotes. |
var='hello world' | Enclosing in single quotes prevents variable expansion. |
var=$(command) | Assigns the output of a command to the variable (command substitution). |
var=$((1 + 2)) | Assigns the result of an arithmetic expression to the variable. |
Referencing Variables
To reference a variable, write $var or ${var}. The brace form makes the variable name boundary explicit, which is useful when concatenating with strings.
| Syntax | Description |
|---|---|
$var | Expands to the value of the variable var. Sufficient when used on its own. |
${var} | Wraps the variable name in braces. Makes the boundary explicit when immediately followed by a string, as in ${var}_suffix. |
"$var" | Enclosing in double quotes treats values containing spaces or newlines as a single string. |
"${var}" | Combines braces and double quotes for the safest reference form. |
${var:-default} | Returns default if the variable is unset or empty (the variable itself is not changed). |
${var:=default} | Assigns default to the variable if it is unset or empty, then returns the value. |
${#var} | Returns the length of the variable's value as a string. |
readonly (Read-only Variables)
A variable declared with readonly cannot be reassigned or deleted with unset afterward. Use it for values you want to treat as constants.
| Syntax | Description |
|---|---|
readonly var=value | Declares and marks the variable as read-only at the same time. |
var=value; readonly var | Assigns a value first, then applies readonly. |
declare -r var=value | Equivalent to readonly. Uses the bash built-in declare command. |
readonly -p | Lists all read-only variables defined in the current shell. |
unset (Deleting Variables)
The unset command deletes a variable. After deletion, referencing the variable returns an empty string. readonly variables cannot be unset.
| Syntax | Description |
|---|---|
unset var | Deletes the variable var. Do not prefix with $. |
unset -v var | Explicitly deletes a variable (the -v flag distinguishes it from a function). |
unset -f func | Deletes the function func. |
Environment Variables and Local Variables
Shell variable scope has two types: local variables and environment variables. Local variables are only valid within the current shell process. Using export promotes them to environment variables, which are inherited by child processes.
| Type | Syntax | Description |
|---|---|---|
| Local variable | var=value | Valid only within the current shell process. Not accessible from child processes (scripts or external commands). |
| Environment variable (export) | export var=value | Inherited by child processes. Accessible from commands and scripts that are run. |
| Local variable inside a function | local var=value | Declares a variable scoped to the function. A bash-specific feature. Not accessible from outside the function. |
| Check environment variables | env or printenv | Lists all current environment variables. |
| Check local variables | set | Lists both shell variables and environment variables. |
Sample Code
psycho_pass_vars.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates variable basics using characters
# from PSYCHO-PASS
# -----------------------------------------------
# -----------------------------------------------
# 1. Assigning and referencing variables
# -----------------------------------------------
# Assignment: no spaces are allowed around =
inspector="Tsunemori Akane"
enforcer="Kougami Shinya"
division="CID Criminal Investigation Department Division 1"
# $var and ${var} — both reference the same value
echo "Inspector: $inspector"
echo "Enforcer: ${enforcer}"
# Use ${var} to make the boundary explicit when concatenating with a string
echo "${inspector} is assigned to ${division}."
# Command substitution: assigns the output of a command to a variable
current_date=$(date '+%Y-%m-%d')
echo "Date recorded: ${current_date}"
echo ""
# -----------------------------------------------
# 2. Default value expansion
# -----------------------------------------------
# hue_level is undefined, so the default value "0" is returned
echo "Hue level: ${hue_level:-0}"
# hue_level itself remains unset (no assignment is made)
echo "Value of hue_level: ${hue_level}" # empty string
# := assigns the default value
echo "Crime coefficient: ${crime_coefficient:=50}"
echo "Value of crime_coefficient: ${crime_coefficient}" # 50 is now assigned
echo ""
# -----------------------------------------------
# 3. readonly — read-only variables
# -----------------------------------------------
readonly SIBYL_SYSTEM="Sibyl System"
echo "Management system: ${SIBYL_SYSTEM}"
# Attempting to reassign causes an error
# SIBYL_SYSTEM="new system" # bash: SIBYL_SYSTEM: readonly variable
echo ""
# -----------------------------------------------
# 4. unset — deleting variables
# -----------------------------------------------
target="Makishima Shogo"
echo "Target (before unset): ${target}"
unset target
echo "Target (after unset): ${target}" # becomes an empty string
echo ""
# -----------------------------------------------
# 5. Local variables and environment variables
# -----------------------------------------------
# Local variable: valid only within the current shell
local_agent="Ginoza Nobuchika"
# Promote to an environment variable with export
export DOMINANT_COLOR="blue"
echo "Local variable local_agent: ${local_agent}"
echo "Environment variable DOMINANT_COLOR: ${DOMINANT_COLOR}"
# Check whether a child process (bash -c) can access each variable
bash -c 'echo "DOMINANT_COLOR from child process: ${DOMINANT_COLOR}"'
bash -c 'echo "local_agent from child process: ${local_agent}"' # becomes an empty string
echo ""
# -----------------------------------------------
# 6. local variables inside a function
# -----------------------------------------------
check_hue() {
# Using local restricts the variable to the function scope
local analyst="Hinakawa Sho"
local status="Analyzing hologram"
echo "[Inside function] Analyst: ${analyst} / Status: ${status}"
}
check_hue
# analyst and status are not accessible outside the function
echo "[Outside function] Analyst: ${analyst}" # becomes an empty string
$ chmod +x psycho_pass_vars.sh $ ./psycho_pass_vars.sh Inspector: Tsunemori Akane Enforcer: Kougami Shinya Tsunemori Akane is assigned to CID Criminal Investigation Department Division 1. Date recorded: 2026-03-27 Hue level: 0 Value of hue_level: Crime coefficient: 50 Value of crime_coefficient: 50 Management system: Sibyl System Target (before unset): Makishima Shogo Target (after unset): Local variable local_agent: Ginoza Nobuchika Environment variable DOMINANT_COLOR: blue DOMINANT_COLOR from child process: blue local_agent from child process: [Inside function] Analyst: Hinakawa Sho / Status: Analyzing hologram [Outside function] Analyst:
When to Use $var vs ${var}
| Situation | Recommended | Reason |
|---|---|---|
| Referencing a variable on its own | "$var" | Double quotes allow values containing spaces or newlines to be handled safely. |
| Immediately followed by a string | "${var}suffix" | Without braces, the shell interprets $varsuffix as a different variable name. |
| Default values, string length, etc. | ${var:-default} / ${#var} | Braces are required because parameter expansion modifiers are written inside them. |
| All elements of an array | "${array[@]}" | Double quotes and braces are both required to expand each element as a separate argument. |
Summary
In shell scripts, variables are assigned with var=value and referenced with $var or ${var}. The most important rule is that no spaces are allowed around = during assignment. Use the brace form when concatenating directly with a string or when using parameter expansion such as ${var:-default}. Using readonly (or declare -r) protects a variable as a constant, preventing both reassignment and unset. To delete a variable, use unset var (without $). Variables created by a plain assignment are local variables, valid only within the current shell process. To pass them to child processes, promote them to environment variables with export. Using local inside a function defines a variable scoped to that function. For more on the difference between environment variables and local variables, see Shell Script Basic Syntax.
If you find any errors or copyright issues, please contact us.