In shell scripting, displaying the value of shell variables is straightforward. You can use the echo command or other utilities like printf to output variable values to the terminal.
Syntax for Displaying Shell Variables
To display the value of a variable, use the $ prefix before the variable name:
echo $variable_name
Methods to Display Shell Variables
- Using echo Command: The most common way to display the value of a variable.
# Define a variable
my_var=”Hello, World!”
# Display its value
echo $my_var
Output:
Hello, World!
- Using printf Command: printf provides more formatting options compared to echo.
my_var=”Hello, World!”
printf “%s\n” $my_var
Output:
Hello, World!
- Using set Command: The set command lists all shell variables and functions, including user-defined and environment variables.
set
Note: This outputs a large list of variables, so you may want to pipe it through grep to filter specific variables.
set | grep my_var
- Using env Command: The env command displays only the environment variables, not user-defined shell variables.
env | grep PATH
- Using declare Command: The declare command shows the attributes and values of variables in the current shell.
declare -p my_var
Output:
declare — my_var=”Hello, World!”
- Using printenv Command: Use printenv to display specific environment variables.
printenv HOME
Examples
Example 1: Display a User-Defined Variable
greeting=”Hello, Linux!”
echo $greeting
Output:
Hello, Linux!
Example 2: Display a Default Environment Variable
echo $HOME
Output:
/home/username
Example 3: Display Multiple Variables
name=”Alice”
age=25
echo “Name: $name, Age: $age”
Output:
Name: Alice, Age: 25
Example 4: Using Variable Expansion with Default Value
echo ${non_existent_var:-“Default Value”}
Output:
Default Value
Special Considerations
- Undefined Variables: Referencing an undefined variable results in an empty string.
echo $undefined_var
# Output: (empty line)
- Quoting Variables: Use quotes when a variable contains spaces or special characters.
my_var=”Hello, World!”
echo “$my_var” # Correct
echo $my_var # May break if spaces exist
- Debugging Variables: To debug or inspect all variables in the script, use:
set
By using these techniques, you can efficiently display and manage shell variables in your scripts or terminal sessions.