BudiBadu Logo
Samplebadu

Bash by Example: Variables

Bash 5.0+

Understanding how to declare, assign, and access variables in Bash with this sample code. Note the strict syntax rules regarding spaces.

Code

#!/bin/bash

# Assignment (NO SPACES around =)
name="John"
age=25

# Accessing variables with $
echo "Name: $name"
echo "Age: $age"

# Best practice: use curly braces for clarity
echo "Greeting: Hello, ${name}!"

# Variable reassignment
name="Jane"
echo "New Name: $name"

# Unsetting a variable
unset name
echo "After unset: '$name'"

Explanation

Variables in Bash are untyped; essentially, everything is stored as a string. To assign a value to a variable, use the syntax var=value. Crucially, there must be no spaces around the equals sign. var = value will be interpreted as running a command named var with arguments = and value, which will result in an error.

To access the value of a variable, you prefix the name with a dollar sign, like $var. For more complex strings or to avoid ambiguity, wrap the variable name in curly braces: ${var}. This is especially important when the variable is immediately followed by other characters (e.g., ${var}_backup).

Variables are mutable by default. You can change their value at any time. To remove a variable, use the unset command. Accessing an undefined or unset variable usually returns an empty string without raising an error, which can sometimes lead to silent bugs.

Code Breakdown

4-5
name="John" demonstrates variable assignment. Note the strict lack of spaces around the equals sign, which is a common pitfall for beginners.
8-9
$name performs variable expansion. The shell replaces the variable name with its value before executing the command.
12
${name} uses curly braces for clarity. This is safer and ensures the shell knows exactly where the variable name ends, preventing ambiguity.
19-20
unset name removes the variable from memory. Subsequent access returns an empty string, effectively treating it as undefined.