Easy Tutorial
❮ Linux Comm Scp Linux Comm Screen ❯

Shell Variables

When defining a variable, do not prefix the variable name with a dollar sign ($), unlike in PHP where it is required. For example:

your_name="tutorialpro.org"

Note that there should be no spaces between the variable name and the equals sign. This is different from most programming languages you might be familiar with. Additionally, variable names must follow these rules:

Examples of valid Shell variable names:

tutorialpro
LD_LIBRARY_PATH
_var
var2

Examples of invalid variable names:

?var=123
user*name=tutorialpro

Besides explicit assignment, you can also assign values to variables using statements, such as:

for file in `ls /etc`
or
for file in $(ls /etc)

The above statements loop through the file names in the /etc directory.


Using Variables

To use a defined variable, simply prefix the variable name with a dollar sign, like so:

Example

your_name="qinjx"
echo $your_name
echo ${your_name}

Braces around the variable name are optional but recommended to help the interpreter identify the variable's boundary. For example:

Example

for skill in Ada Coffee Action Java; do
    echo "I am good at ${skill}Script"
done

If braces are not used for the skill variable, writing echo "I am good at $skillScript" would cause the interpreter to treat $skillScript as a variable (with an empty value), leading to unexpected results.

It is a good practice to always use braces for variables.

Defined variables can be redefined, like so:

Example

your_name="tom"
echo $your_name
your_name="alibaba"
echo $your_name

This is legal, but note that you cannot write $your_name="alibaba" during reassignment; the dollar sign is only used when referencing the variable.

Read-Only Variables

Using the readonly command, you can define a variable as read-only, and its value cannot be changed.

The following example attempts to change a read-only variable, resulting in an error:

Example

#!/bin/bash

myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.tutorialpro.org"

Running the script results in:

/bin/sh: NAME: This variable is read only.

Deleting Variables

Variables can be deleted using the unset command. Syntax:

unset variable_name

Deleted variables cannot be used again. The unset command cannot delete read-only variables.

Example

Example

#!/bin/sh

myUrl="https://www.tutorialpro.org"
unset myUrl
echo $myUrl

The above example will produce no output.

Variable Types

When running a shell, three types of variables coexist:

-1) Local Variables Defined in a script or command, valid only within the current shell instance. Programs started by other shells cannot access local variables.

-2) Environment Variables Accessible by all programs, including those started by the shell. Some programs require environment variables to function correctly. Environment variables can also be defined in shell scripts.

-3) Shell Variables Special variables set by the shell program. Some of these are environment variables, and some are local variables, ensuring the shell's proper operation.


Shell Strings

Strings are the most commonly used and useful data types in shell programming (besides numbers and strings, there aren't many other types to use). Strings can be enclosed in single quotes, double quotes, or no quotes at all.

Single Quotes

str='this is a string'

Restrictions of single-quoted strings:

Double Quotes

Example

your_name="tutorialpro"
str="Hello, I know you are \"$your_name\"! \n"
echo -e $str

Output:

Hello, I know you are "tutorialpro"!

Advantages of double-quoted strings:

Example

your_name="tutorialpro"
# Using double quotes for concatenation
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting  $greeting_1

# Using single quotes for concatenation
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2  $greeting_3

Output result:

hello, tutorialpro ! hello, tutorialpro !
hello, tutorialpro ! hello, ${your_name} !

Get String Length

Example

string="abcd"
echo ${#string}   # Outputs 4

When the variable is an array, ${#string} is equivalent to ${#string[0]}:

Example

string="abcd"
echo ${#string[0]}   # Outputs 4

Extract Substring

The following example extracts 4 characters starting from the 2nd character:

Example

string="tutorialpro is a great site"
echo ${string:1:4} # Outputs unoo

Note: The index of the first character is 0.

Find Substring

Find the position of the characters i or o (whichever appears first):

Example

string="tutorialpro is a great site"
echo `expr index "$string" io`  # Outputs 4

Note: In the above script, ``is a backtick, not a single quote'`, don't confuse them.


Shell Arrays

Bash supports one-dimensional arrays (does not support multi-dimensional arrays) and does not limit the size of the array.

Similar to C language, the subscript of array elements starts from 0. To get elements in the array, use the subscript, which can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.

Define Array

In Shell, parentheses are used to represent arrays, and array elements are separated by "spaces". The general form of defining an array is:

array_name=(value1 value2 ... valuen)

For example:

array_name=(value0 value1 value2 value3)

Or

array_name=(
value0
value1
value2
value3
)

You can also define individual components of the array separately:

array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen

Subscripts do not need to be continuous, and there is no limit to the range of subscripts.

Read Array

The general format for reading array element values is:

${array_name[subscript]}

For example:

valuen=${array_name[n]}

Using the @ symbol, you can get all elements of the array, for example:

echo ${array_name[@]}

Get Array Length

The method to get the length of an array is the same as that for getting the length of a string, for example:

Example

# Get the number of array elements
length=${#array_name[@]}
# Or
length=${#array_name[*]}
# Get the length of a single element in the array
lengthn=${#array_name[n]}

Shell Comments

A line starting with # is a comment and will be ignored by the interpreter.

To set multi-line comments by adding a # at the beginning of each line, like this:

Example

#--------------------------------------------
# This is a comment
# author: tutorialpro.org
# site: www.tutorialpro.org
# slogan: Learning is not only about technology, it's about dreams!
#--------------------------------------------
##### User Configuration Area Start #####
#
#
# Here you can add script description information
# 
#
##### User Configuration Area End  #####

If you need to temporarily comment out a large block of code during development and then uncomment it later, what should you do?

Adding a # to every line is too laborious. You can enclose the block of code you want to comment out with a pair of curly braces, define it as a function, and if there is no place to call this function, this block of code will not be executed, achieving the same effect as a comment.

Multi-line Comments

Multi-line comments can also be used in the following format:

:<&lt;EOF
Comment content...
Comment content...
Comment content...
EOF

EOF can also be replaced with other symbols:

Example

:<<'
Comment content...
Comment content...
Comment content...
'

:<<!
Comment content...

Note content... Note content... !

❮ Linux Comm Scp Linux Comm Screen ❯