What are Linux Bash Variables?
Variables in Linux Bash are used to store data that can be referenced and manipulated throughout your script. They are essential for creating dynamic and flexible scripts.
Defining Variables
To define a variable in Bash, you simply assign a value to a name. Here’s the basic syntax:
variable_name=value
Example:
greeting="Hello, World!"
Accessing Variables
To access the value of a variable, you use the $
symbol followed by the variable name.
echo $greeting
This will output:
Hello, World!
Types of Variables
- Local Variables: These are defined within a function and are only accessible within that function.
- Global Variables: These are defined outside of all functions and are accessible from anywhere in the script.
- Environment Variables: These are global variables that are available to any child process of the shell.
Common Environment Variables
Some commonly used environment variables include:
PATH
: Specifies the directories in which the shell looks for executable files.HOME
: Indicates the home directory of the current user.USER
: Contains the name of the current user.SHELL
: Specifies the path to the current shell.LANG
: Defines the language and locale settings.PWD
: Represents the current working directory.
List and Read Environment Variables
You can list all environment variables using commands like printenv
, env
, or set
:
printenv
: Displays all or specific environment variables.env
: Shows all environment variables.set
: Lists all shell variables, including environment variables.
To access to the envoronment variables you can do the following:
echo $SHELL
This will output:
/bin/bash
Setting Environment Variables
You can set environment variables in the shell using the export
command. For example:
export MY_VARIABLE="some_value"
This sets MY_VARIABLE
to “some_value” for the current session.
Accessing Environment Variables
To access the value of an environment variable, you use the $
symbol followed by the variable name. For example:
echo $MY_VARIABLE
Persisting Environment Variables
To make environment variables persistent across sessions, add them to your shell’s configuration file (e.g., .bashrc
or .bash_profile
).
Example:
nano .bashrc
# Add the variable at the end of file
GREETING="Hello, World!"
Reload the profile:
source ~/.bash_profile
Access to the defined variable:
echo $GREETING
Output:
Hello, World!
Special Variables
Bash also has several special variables that are predefined and have specific meanings:
$0
: The name of the script.$1, $2, ...
: The positional parameters.$#
: The number of positional parameters.$@
: All the positional parameters.$$
: The process ID of the current shell.$?
: The exit status of the last command executed.