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.
echo $var
# or
echo ${var}name="Alice"
echo $namename="Alice"
echo Hello, ${name}!count=5 echo "Count is $count"
var="world" echo "Hello, ${var}ly!"
#!/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}"
${var} instead of just $var?$var accesses the value of a variable named var.${var} helps separate the variable name from other text, avoiding confusion when concatenating.name followed immediately by the string _end in bash?name followed by _end, we must separate the variable name from the string.${name}_end correctly prints the variable value plus the string _end. Without braces, $name_end looks for a variable named name_end.var="world"
echo "Hello $var!"
echo "Hello ${var}!"
echo "Hello $var123"
echo "Hello ${var}123"filename="report" echo "File: $filename.txt"
File: report.txt as expected?$filename.txt makes bash look for variable named filename.txt, which does not exist.${filename}.txt correctly expands filename and appends .txt.user followed by the string _backup only if user is not empty. Which is the best way to write the echo command?${user:+${user}_backup} prints ${user}_backup only if user is not empty._backup even if user is empty. echo "$user_backup" looks for variable user_backup. echo "${user}_backup" && [ -n "$user" ] has wrong syntax mixing echo and condition.Pass the test and this pattern moves unknown