0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Variables in Bash: Syntax and Examples

In Bash, you create a variable by writing its name followed by an equal sign and the value without spaces, like name=value. To use the variable's value, prefix its name with a dollar sign, for example, $name.
📐

Syntax

To create a variable in Bash, write the variable name, then an equal sign =, and then the value with no spaces around the equal sign. To use the variable, prefix its name with $.

  • Variable assignment: variable_name=value
  • Variable usage: $variable_name
bash
variable_name=value

# Use the variable
 echo $variable_name
💻

Example

This example shows how to assign a value to a variable and then print it using echo. It demonstrates the basic use of variables in Bash scripts.

bash
#!/bin/bash

name=Alice

echo "Hello, $name!"
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes include putting spaces around the equal sign during assignment, which causes errors, and forgetting to use $ when accessing the variable's value.

Also, quoting matters: use quotes around variables when the value contains spaces to avoid word splitting.

bash
# Wrong: spaces around = cause error
# name = Alice

# Correct:
name=Alice

# Wrong: missing $ when using variable
# echo name

# Correct:
echo $name

# Handling spaces in values
full_name="Alice Smith"
echo "$full_name"
Output
Alice Alice Smith
📊

Quick Reference

ActionSyntaxExample
Assign a variablevariable=valuename=Bob
Use a variable$variableecho $name
Assign with spacesvariable="value with spaces"full_name="Bob Smith"
Use variable in string"Hello, $variable!"echo "Hello, $name!"

Key Takeaways

Assign variables without spaces around the equal sign, like name=Alice.
Use $ before the variable name to access its value, for example, $name.
Quote variables when their values contain spaces to preserve them.
Avoid common mistakes like spaces in assignment or missing $ when using variables.