Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Shell Variables

Shell Variables

In Shell programming, a variable is a name used to store a data value.

When defining a variable, the variable name is not prefixed with a dollar sign ($; it is required in PHP), for example:

your_name

=

"runoob"

Note that there can be no spaces between the variable name and the equal sign, which may be different from all programming languages you are familiar with. At the same time, variable names must follow these rules:

Examples of valid Shell variable names:


RUNOOB="www.runoob.com"
LD_LIBRARY_PATH="/bin/"
_var="123"
var2="abc"

Invalid variable names:


# Avoid using if as a variable name
if="some_value"
# Avoid using special symbols like $
variable_with_$=42
?var=123
user*name=runoob
# Avoid spaces
variable with space="value"

Avoid spaces on either side of the equal sign:

# 正确的赋值
variable_name=value

# May potentially cause errors
variable_name = value

Besides explicit direct assignment, you can also use statements to assign values to variables, for example:

for

file

in

`

ls

/

etc

`

or

for

file

in

$

(

ls

/

etc

)

The above statement loops through the filenames of the directories under /etc.


Using variables

To use a variable that has been defined, just add a dollar sign in front of the variable name, for example:

Example

your_name

=

"qinjx"

echo

$your_name

echo

${your_name}

The curly braces around a variable name are optional; adding them helps the interpreter identify the variable's boundary, for example in the following case:

Example

for

skill

in

Ada Coffe Action Java;

do

   

echo

"I am good at ${skill}Script"

done

If you do not add curly braces to the skill variable and write echo "I am good at $skillScript", the interpreter will treat $skillScript as one variable (whose value is empty), and the code will not produce the expected result.

It is recommended to add curly braces to all variables; this is a good programming habit.

A defined variable can be redefined, for example:

Example

your_name

=

"tom"

echo

$your_name

your_name

=

"alibaba"

echo

$your_name

This is legal, but note that on the second assignment you cannot write $your_name="alibaba"; the dollar sign ($) is added only when using the variable.

Read-only variables

Use the readonly command to define a variable as read-only; the value of a read-only variable cannot be changed.

The following example tries to change a read-only variable and results in an error:

Example

#!/bin/bash

myUrl

=

"https://www.google.com"

readonly

myUrl

myUrl

=

"https://www.runoob.com"

Run the script, and the result is as follows:


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

Deleting variables

Use the unset command to delete a variable. Syntax:

unset variable_name

A deleted variable cannot be used again. The unset command cannot delete read-only variables.

Example

Example

#!/bin/sh

myUrl

=

"https://www.runoob.com"

unset

myUrl

echo

$myUrl

The above example produces no output when executed.

Variable Types

Shell supports different types of variables; some of the main types include:

String variables: In Shell, variables are generally treated as strings.

You can use single quotes ' or double quotes " to define a string, for example:

my_string='Hello, World!'

或者

my_string="Hello, World!"

Integer variables: In some shells, you can use declare or typeset to declare an integer variable.

Such a variable contains only integer values, for example:


declare -i my_integer=42

Such a declaration tells Shell to treat my_integer as an integer; if you try to assign a non-integer value to it, Shell will attempt to convert it to an integer.

Array variables: Shell also supports arrays, allowing you to store multiple values in a single variable.

Arrays can be integer-indexed or associative; here is a simple example of an integer-indexed array:

my_array=(1 2 3 4 5)

Or an associative array:

declare -A associative_array
associative_array["name"]="John"
associative_array["age"]=30

Environment variables: These are special variables set by the operating system or the user, used to configure Shell behavior and affect its execution environment.

For example, the PATH variable contains the paths where the operating system searches for executable files:

echo $PATH

Special variables: Some special variables have special meanings in Shell: for example, $0 represents the script name, and $1, $2, etc. represent the script's arguments.

$# represents the number of arguments passed to the script, and $? represents the exit status of the previous command, and so on.


Shell Strings

Strings are the most commonly used and useful data type in shell programming (apart from numbers and strings, there are not really any other useful types). A string can use single quotes, double quotes, or no quotes at all.

Single quote


str='this is a string'

Limitations of single-quoted strings:

Double quote

Example

your_name

=

"runoob"

str

=

"Hello, I know you are "$your_name"! \n"

echo

-e

$str

The output is:

Hello, I know you are "runoob"! 

Advantages of double quotes:

Concatenating strings

Example

your_name

=

"runoob"

Concatenating with double quotes

greeting

=

"hello, "

$your_name

" !"

greeting_1

=

"hello, ${your_name} !"

echo

$greeting

 

$greeting_1

Concatenating with single quotes

greeting_2

=

'hello, '

$your_name

' !'

greeting_3

=

'hello, ${your_name} !'

echo

$greeting_2

 

$greeting_3

The output is:

hello, runoob ! hello, runoob !
hello, runoob ! hello, ${your_name} !

Getting the string length

Example

string

=

"abcd"

echo

${#string}

 

Output 4

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

Example

string

=

"abcd"

echo

${#string[0]}

 

Output 4

Extracting a substring

The following example starts from the 2 th character of the string and extracts 4 characters:

Example

string

=

"runoob is a great site"

echo

${string:1:4}

Output unoo

Note: The index of the first character is 0.

Find a substring

Finding a character i or o 's position (whichever letter appears first is the one counted):

Example

string

=

"runoob is a great site"

echo

`

expr

index

"$string"

io

`

 

Output 4

Note: In the above script, ` is a backtick, not a single quote '; be careful not to mix them up.


Shell Arrays

bash supports one-dimensional arrays (not multidimensional arrays) and does not limit the array size.

Similar to the C language, array elements are indexed starting from 0. To access an element in an array you use its index, which can be an integer or an arithmetic expression whose value must be greater than or equal to 0.

Defining an array

In Shell, arrays are represented with parentheses, and array elements are separated by spaces. The general form for defining an array is:


数组名=(值1 值2 ... 值n)

For example:


array_name=(value0 value1 value2 value3)

or


array_name=(
value0
value1
value2
value3
)

You can also define individual elements of the array separately:


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

Indices do not have to be consecutive, and there is no limit on their range.

Reading arrays

The general format for reading an array element's value is:


${数组名[下标]}

For example:


valuen=${array_name[n]}

Use the @ symbol to get all elements of an array, for example:


echo ${array_name[@]}

Getting the length of an array

The method for getting an array's length is the same as for getting a string's length, for example:

Example

Get the number of array elements

length

=

${#array_name[@]}

or

length

=

${#array_name[*]}

Get the length of a single array element

length

=

${#array_name[n]}


Shell Comments

A line beginning with # is a comment and is ignored by the interpreter.

By adding a # to each line, you can set up a multi-line comment, like this:

Example

#--------------------------------------------

This is a comment

author:Runoob Tutorial

site:www.runoob.com

slogan: What you learn is not just technology, but also dreams!

#--------------------------------------------

User Configuration Area Start

You can add script description information here

User Configuration Area End #####

If during development you encounter a large block of code that needs to be temporarily commented out and then uncommented later, what should you do?

Adding a # to every line is too much work. You can wrap the code to be commented in a pair of curly braces and define it as a function; since the function is never called, the code will not execute, achieving the same effect as a comment.

Multi-line comment

Using a Here Document

Multi-line comments can also use the following format:

:

< Comment content...
Comment content...
Comment content...
EOF

In the above example,

:

is a null command used to execute the following Here Document,

<<'EOF'

indicates the start of the Here Document, COMMENT is the identifier of the Here Document, and everything between these two identifiers is treated as a comment and is not executed.

EOF can also be replaced with other symbols:

Example

:

<<'COMMENT'
This is the commented part.
It can contain multiple lines.
COMMENT

:

<<

'
Comment content...
Comment content...
Comment content...
'

:

<

Comment content...

Comment content...

Comment content...

!

Directly using the : symbol

We can also use the colon : command and enclose multiple lines in single quotes '. Since colon is a null command, this content will not be executed.

The format is: : + space + single quote.

Example

:

'
This is the commented part.
It can contain multiple lines.
'