Variables in Bash are used to store values such as text, numbers, or even the result of a command. They allow you to reuse and manipulate data throughout your script. Bash variables are flexible, but there are a few important rules and types to understand: user-declared, environment, local/global scope, and how to perform operations like concatenation or arithmetic.
Bash Variable Examples
1. Declare and use a simple variable:
Bash variables are created by assigning a value with = and used by placing a $ before the variable name.
2. Environment Variables
Environment variables are special system-wide variables used to configure the shell or software.
This prints the value of the built-in HOME environment variable. You can also create your own environment variable:
3. Local vs. Global Variables
Variables declared inside functions are local by default if specified with local. Otherwise, they are global within the script.
myvar="Global"
my_function() {
local myvar="Local"
echo "Inside function: $myvar"
}
my_function
echo "Outside function: $myvar"
This shows how local limits the scope of a variable to inside the function.
4. Common Variable Operations
- Concatenation (Combining Strings)
You can join strings by simply placing them next to each other:
- Arithmetic with Numbers
Use (( )) or let for performing math operations with numeric variables:
Or using let:
Important Points
- No spaces around the equal sign when assigning variables.
- Variables are case-sensitive.
NAMEis different fromname. - Use
exportto make a variable available to child processes. - Use
localinside functions to limit a variable’s scope.
Try It Out!
Create a script that combines two strings into one message. Try to store two numbers and print their product using (( )) too.
TD Bash PlayCloud
Please click the “Play” button to launch the terminal and wait for it to load. If you’re unable to type, kindly click the refresh button located at the upper right corner.