Variables in Bash
In Bash scripting, variables are used to store data that can be used later in the script. Here’s a quick overview of how to work with variables in Bash:
Defining Variables
Variables in Bash are defined by assigning a value to a name, with no spaces around the =
sign:
1 | variable_name=value |
For example:
1 | name="Johnson" |
Note that there should be no spaces between the variable name and the equals sign, which might differ from what you’re used to in other programming languages. Variable names must follow these rules:
- Contain only letters, numbers, and underscores: Variable names can include letters (case-sensitive), numbers, and underscores (_), but no other special characters.
- Not start with a number: While variable names can include numbers, they cannot begin with one.
- Avoid Shell keywords: Do not use Shell keywords (e.g., if, then, else, fi, for, while) as variable names to prevent confusion.
- Use uppercase for constants: By convention, variable names for constants are typically written in uppercase, like PI=3.14.
- Avoid special symbols: Try to avoid special symbols in variable names as they may conflict with Shell syntax.
- No spaces: Variable names should not include spaces, as spaces are generally used to separate commands and arguments.
Examples of valid Shell variable names are as follows:
1 | HOSTNAME="www.linjiangxiong.com" |
Examples of invalid variable naming are as follows:
1 | # Avoid using reserved keywords like "else" as variable names. |
Avoid using spaces around the equal sign:
1 | # Correct assignment |
In addition to direct assignment, you can also assign values using statements, such as:
1 | for file in $(ls /home/john/); |
This loop iterates over the filenames in the
/home/john
directory.
Using Variables
To use the value of a variable, prefix its name with a dollar sign $
:
1 | name="Johnson" |
This will output:
1 | Johnson |
Note: Braces around variable names are optional but can help the interpreter recognize the boundaries of the variable. For example:
1 | for ball_type in Foot Base Basket Volley; do |
Without braces, if you write
echo "I like $ball_typeball"
, the interpreter will treat $ball_typeball
as a single variable (which will be empty), leading to unexpected results.
Defined variables can be reassigned, as shown in the example below. Note that when reassigning a variable, you should not use the dollar sign ($
). The dollar sign is only needed when referencing the variable’s value.
1 | # Define a variable your_name and set it to "john" |
Read-Only Variables
The readonly
command can be used to define a variable as read-only, meaning its value cannot be changed. The following example attempts to modify a read-only variable, which results in an error.
1 |
|
Running the script produces the following result:
1 | xxxx.sh: 5: name: is read only |
Unsetting Variables
To remove a variable, use the unset
command:
1 | unset variable_name |
Once a variable is deleted, it cannot be used again. For example, running the following code will produce no output.
1 |
|
Note: The
unset
command cannot remove read-only variables. For example, running the following code will produce the error message unset: first_name: is read only
.1 |
|
Local Variables
Within functions, you can declare local variables using the local
keyword:
1 | func() { |
Global vs Local Variables
Global variables are accessible throughout the entire script, while local variables are only accessible within their defined scope, such as inside a function.
For example:
1 |
|
When you execute the script:
1 | $ sh t9.sh |
You will see:
1 | local variable value |
This output demonstrates that the local variable is only accessible within the function, while the global variable is accessible both inside and outside the function.
System Variables
System variables define various aspects of the shell and are managed by Bash itself. However, you can modify these variables to change shell behavior.
To list all available system variables and their values, type env
in the Bash shell:
1 | $ env |
These variables are typically written in uppercase letters, such as PATH, SHELL, HOME, LANG, PWD, and many others.
For example:
1 | $ echo $PATH |
Special Variables
Bash also has several special variables:
$0
: The name of the script.$1
,$2
, …,$n
: Positional parameters (arguments to the script).$#
: The number of positional parameters.$@
: All positional parameters as separate words.$*
: All positional parameters as a single word.- $$$$: The process ID of the script.
$?
: The exit status of the last command.
For example, create a shell script special_variables_example.sh
using following code.
1 |
|
Let’s execute the script:
1 | $ sh special_variables_example.sh arg1 arg2 arg3 |
It will output:
1 | Print the name of the script itself: special_variables_example.sh |
Reading User Input
You can read user input into a variable using the read
command:
1 | read -p "Enter your name: " user_name |
The value entered by the user will be stored in the
user_name
variable.For example, running the following code will produce the message
Hello, Johnson
.1 |
|
Output:
1 | $ sh read_input_example.sh |
Exporting Variables
To make a variable available to subprocesses or child scripts, use the export
command:
1 | export MY_VAR="some value" |
In a child script or process, you can access
MY_VAR
like any other variable.
Variable Substitution
Bash supports various types of variable substitution:
Default Values: Use
${VAR:-default}
to provide a default value ifVAR
is unset or null.bash1
echo ${name:-"Unknown"}
Substring Extraction: Use
${VAR:offset:length}
to extract a substring.bash1
2full_name="Alice Smith"
first_name=${full_name:0:5} # Extracts "Alice"String Replacement: Use
${VAR/old/new}
to replace the first occurrence ofold
withnew
.bash1
2path="/usr/local/bin"
new_path=${path/bin/exe} # Results in "/usr/local/exe"