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
2
name="Johnson"
age=28

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
2
3
4
HOSTNAME="www.linjiangxiong.com"
FILEBEAT_HOME="/opt/filebeat"
_rvm_version="1.29.12"
flag2="35609"

Examples of invalid variable naming are as follows:

1
2
3
4
5
6
7
8
9
10
11
12
# Avoid using reserved keywords like "else" as variable names.
# Using Shell keywords as variable names may not cause errors,
# but it can lead to confusion.
else="variable_with_reserved_keywords_else"

# Avoid using special characters like $, ?, *, # in variable names
var_$=42
?_var=123
user_*_name=johnson

# Avoid using spaces in variable names
user name=johnson

Avoid using spaces around the equal sign:

1
2
3
4
5
# Correct assignment
variable_name=value

# May cause errors: 'variable_name: not found'
variable_name = "using spaces around the equal sign"

In addition to direct assignment, you can also assign values using statements, such as:

1
2
3
4
for file in $(ls /home/john/);
do
echo $file
done;

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
2
name="Johnson"
echo $name

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
2
3
for ball_type in Foot Base Basket Volley; do
echo "I like ${ball_type}ball"
done

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
2
3
4
5
6
7
8
9
10
11
12
13
# Define a variable your_name and set it to "john"
your_name="john"
# Print the value of the variable your_name
echo $your_name

# Change the value of your_name to "johnson"
your_name="johnson"
# Print the new value of the variable your_name
echo $your_name

# This line of code has a syntax error
$your_name="oihre"
echo $your_name

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
2
3
4
5
#!/bin/bash

name="Johnson"
readonly name
name="John"

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
2
3
4
5
#!/bin/bash

name="Johnson"
unset name
echo $name

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
2
3
4
5
6
#!/bin/bash

first_name="DD"
readonly first_name
unset first_name
echo $first_name

Local Variables

Within functions, you can declare local variables using the local keyword:

1
2
3
4
5
6
7
func() {
# Define a local variable within the function
local greeting="Hello"

# Output the local variable (accessible within the function)
echo "$greeting, John!"
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash

# Define a global variable
GLOBAL_VAR="global variable value"

func() {
# Define a local variable within the function
local local_var="local variable value"

# Output the local variable (accessible within the function)
echo $local_var

# Output the global variable (accessible within the function)
echo $GLOBAL_VAR
}

# Call the function
func

# Attempt to access the local variable (this will fail, as it's only accessible within the function)
echo $local_var

# Output the global variable (accessible outside the function)
echo $GLOBAL_VAR

When you execute the script:

1
$ sh t9.sh

You will see:

1
2
3
4
local variable value
global variable value

global 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
2
3
4
5
6
7
8
9
10
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin
$ echo $SHELL
/bin/bash
$ echo $HOME
/home/john
$ echo $LANG
en_US.UTF-8
$ echo $PWD
/home/johnson

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

echo "Print the name of the script itself: $0"

echo "Print the first argument passed to the script: $1"

echo "Print the second argument passed to the script: $2"

echo "Print the total number of arguments passed to the script: $#"

echo "Print all the arguments passed to the script as a single string, with each argument separated by a space: $@"

echo "Print all the arguments passed to the script as a single string, with each argument separated by the first character of the IFS variable (usually space): $*"

echo "Print the process ID of the current shell: $$"

echo "Print the exit status of the last command executed: $?"

Let’s execute the script:

1
$ sh special_variables_example.sh arg1 arg2 arg3

It will output:

1
2
3
4
5
6
7
8
9
Print the name of the script itself: special_variables_example.sh
Print the first argument passed to the script: arg1
Print the second argument passed to the script: arg2
Print the total number of arguments passed to the script: 3
Print all the arguments passed to the script as a single string, with each argument separated by a space: arg1 arg2 arg3
Print all the arguments passed to the script as a single string, with each argument separated by the first character of the IFS variable (usually space): arg1 arg2 arg3
Print the process ID of the current shell: 27033
Print the exit status of the last command executed: 0

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
2
3
4
5
#!/bin/bash

read -p "Enter your name: " user_name

echo "Hello, $user_name"

Output:

1
2
3
$ sh read_input_example.sh 
Enter your name: Johnson
Hello, Johnson

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 if VAR is unset or null.

    1
    echo ${name:-"Unknown"}
  • Substring Extraction: Use ${VAR:offset:length} to extract a substring.

    1
    2
    full_name="Alice Smith"
    first_name=${full_name:0:5} # Extracts "Alice"
  • String Replacement: Use ${VAR/old/new} to replace the first occurrence of old with new.

    1
    2
    path="/usr/local/bin"
    new_path=${path/bin/exe} # Results in "/usr/local/exe"