Variable Reference and Manipulation
Once you have declared a variable in Bash, you can reference its value and perform various manipulations on it. In this section, we will explore how to work with variables, including referencing, assignment, and scope.
Variable Referencing
As mentioned earlier, you can reference a variable's value by prefixing the variable name with the $
symbol. This allows you to use the variable's value within your scripts. For example:
name="John Doe"
echo "Hello, $name!"
You can also use curly braces {}
to enclose the variable name when it's part of a larger string:
name="John Doe"
echo "Hello, ${name}!"
This can be useful when the variable is part of a larger expression or when you need to differentiate the variable from surrounding text.
Variable Assignment
In addition to the initial declaration, you can also assign new values to variables at any point in your script. This is done using the same syntax as the initial declaration:
name="John Doe"
name="Jane Doe" ## Reassigning the value of the 'name' variable
You can also perform arithmetic operations on numeric variables using the $((expression))
syntax:
age=30
age=$((age + 1)) ## Incrementing the 'age' variable by 1
Variable Scope
In Bash, variables can have different scopes, which determine where they can be accessed and modified. The main scopes are:
- Global variables: These are variables that are accessible throughout your entire script.
- Local variables: These are variables that are only accessible within the function or block of code where they are defined.
By default, variables in Bash are global. To create a local variable, you can use the local
keyword:
function greet() {
local name="John Doe"
echo "Hello, $name!"
}
greet ## Output: Hello, John Doe!
echo "$name" ## Output: (empty)
In this example, the name
variable is local to the greet()
function and cannot be accessed outside of it.