Introduction to Shell Variables
What are Shell Variables?
Shell variables are a fundamental concept in shell scripting. They are essentially named storage locations that can hold values, which can be used throughout the script. Shell variables can store various types of data, such as strings, numbers, and even command outputs.
Declaring and Assigning Values to Shell Variables
To declare a shell variable, you simply need to assign a value to it using the =
operator. For example:
my_variable="Hello, LabEx!"
In this example, my_variable
is the name of the shell variable, and "Hello, LabEx!"
is the value assigned to it.
You can also declare and assign values to multiple variables at once:
name="LabEx" age=30 email="[email protected]"
Accessing the Value of a Shell Variable
To access the value of a shell variable, you need to prefix the variable name with a $
symbol. For example:
echo $my_variable ## Output: Hello, LabEx!
echo "My name is $name and I'm $age years old." ## Output: My name is LabEx and I'm 30 years old.
Variable Scope
Shell variables can have different scopes, which determine where they are accessible. The two main scopes are:
- Local Variables: Variables that are only accessible within the current shell session or script.
- Environment Variables: Variables that are accessible to the shell and all the processes it spawns.
We'll explore the usage of these special variables in the next section.