Bash by Example: Variables
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
name="John" demonstrates variable assignment. Note the strict lack of spaces around the equals sign, which is a common pitfall for beginners.$name performs variable expansion. The shell replaces the variable name with its value before executing the command.${name} uses curly braces for clarity. This is safer and ensures the shell knows exactly where the variable name ends, preventing ambiguity.unset name removes the variable from memory. Subsequent access returns an empty string, effectively treating it as undefined.
