0
0
Bash Scriptingscripting~5 mins

Accessing variables ($var and ${var}) in Bash Scripting

Choose your learning style9 modes available
Introduction
You use variables to store information and access their values easily in your script. Accessing variables with $var or ${var} lets you use the stored value wherever you need it.
When you want to print a stored value in your script.
When you need to combine a variable with other text or characters.
When you want to pass a variable's value as input to a command.
When you want to check or compare the value stored in a variable.
When you want to use variables inside strings or commands safely.
Syntax
Bash Scripting
echo $var
# or
echo ${var}
Use $var to access the value of a variable named var.
Use ${var} when you want to clearly separate the variable name from surrounding text.
Examples
Prints the value of the variable 'name'.
Bash Scripting
name="Alice"
echo $name
Uses ${name} to combine the variable with other text safely.
Bash Scripting
name="Alice"
echo Hello, ${name}!
Prints the value of 'count' inside a string.
Bash Scripting
count=5
echo "Count is $count"
Without braces, $var would be followed by 'ly' as part of the name. Braces separate the variable name.
Bash Scripting
var="world"
echo "Hello, ${var}ly!"
Sample Program
This script shows how to access variables with $var and ${var}. It also shows why braces are useful to separate variable names from text.
Bash Scripting
#!/bin/bash

user="Bob"

# Access variable without braces
 echo "Hello, $user"

# Access variable with braces and extra text
 echo "Hello, ${user}123"

# Show difference without braces
 echo "Hello, $user123"

# Assign a new variable
user123="Not Bob"

# Now print user123
 echo "Hello, ${user} and ${user123}"
OutputSuccess
Important Notes
Always use braces ${var} when you add letters or numbers right after the variable name to avoid confusion.
Variables are case sensitive in bash, so $User and $user are different.
You can use variables inside double quotes "" but not inside single quotes ''.
Summary
Use $var to access a variable's value simply.
Use ${var} to clearly separate the variable name from other text.
Braces help avoid mistakes when combining variables with other characters.