How to Declare Variables in Bash: Simple Syntax and Examples
In Bash, you declare a variable by writing its name followed by an equals sign and the value without spaces, like
name=value. You can then use the variable by prefixing it with a dollar sign, for example, $name.Syntax
To declare a variable in Bash, use the format variable_name=value without spaces around the equals sign. Variable names can include letters, numbers, and underscores but cannot start with a number. To access the value, prefix the variable name with a dollar sign $.
bash
variable_name=value # Example: name=John # Accessing the variable: echo $name
Example
This example shows how to declare a variable and print its value using echo. It demonstrates storing a string and then displaying it.
bash
# Declare a variable
name=Alice
# Print the variable's value
echo "Hello, $name!"Output
Hello, Alice!
Common Pitfalls
Common mistakes include putting spaces around the equals sign, which causes errors, or forgetting to use $ when accessing the variable. Also, variables are case-sensitive, so name and Name are different.
bash
# Wrong: spaces around = cause error # name = John # Right: no spaces name=John # Wrong: missing $ when accessing # echo name # Right: use $ to access name=John echo $name
Output
John
Quick Reference
| Action | Syntax | Notes |
|---|---|---|
| Declare variable | variable_name=value | No spaces around = |
| Access variable | $variable_name | Use $ to get value |
| Assign string with spaces | variable_name="value with spaces" | Use quotes for spaces |
| Unset variable | unset variable_name | Removes the variable |
Key Takeaways
Declare variables without spaces around the equals sign.
Use $ before the variable name to access its value.
Variable names are case-sensitive and cannot start with numbers.
Use quotes when assigning values with spaces.
Avoid common errors like spaces around = or missing $ when accessing.