Different Ways to Print Variable Values
Now that you understand the basics of creating variables, let's explore different methods to print their values in shell scripts.
Using Double Quotes
The most common way to print variables is using double quotes with the echo
command. Double quotes allow the shell to interpret variable names and substitute their values.
Create a new file named print_variables.sh
:
- Click on the "New File" icon in the WebIDE
- Name it
print_variables.sh
- Add the following content:
#!/bin/bash
## Declaring variables
name="LabEx"
version=1.0
is_active=true
## Printing variables with double quotes
echo "Application name: $name"
echo "Version: $version"
echo "Active status: $is_active"
## Printing multiple variables in one statement
echo "The $name application version $version is $is_active"
- Save the file (Ctrl+S or File > Save)
- Make it executable:
chmod +x print_variables.sh
- Run the script:
./print_variables.sh
You should see output similar to:
Application name: LabEx
Version: 1.0
Active status: true
The LabEx application version 1.0 is true
Using Curly Braces
Sometimes you need to be more precise about where a variable name begins and ends. Curly braces help with this by clearly delineating the variable name.
Add the following lines to your print_variables.sh
script:
## Using curly braces to clearly define variable boundaries
app="${name}App"
echo "Application full name: $app"
## This avoids confusion when you want to append text directly to a variable's value
echo "Application name with text: ${name}Text"
Save and run the script again:
./print_variables.sh
The additional output should show:
Application full name: LabExApp
Application name with text: LabExText
Using Single Quotes
Unlike double quotes, single quotes prevent variable substitution and print the literal text.
Add these lines to your script:
## Using single quotes (no variable substitution)
echo 'With single quotes: $name is not replaced'
## Mixing quote types for complex output
echo "This is the variable value: '$name'"
Save and run the script again. You should see:
With single quotes: $name is not replaced
This is the variable value: 'LabEx'
The printf
command offers more control over the formatting of your output:
## Using printf for formatted output
printf "Name: %s\nVersion: %.1f\n" "$name" "$version"
## Formatting numbers with printf
number=42.5678
printf "Formatted number: %.2f\n" $number
Save and run the script again. The additional output will show:
Name: LabEx
Version: 1.0
Formatted number: 42.57
Try experimenting with the different printing methods to see which ones work best for your needs.