Shell 变量


When defining a variable, do not add a dollar sign ($, required for variables in PHP language) in the variable name, such as:

your_name="php.cn"

Note that there cannot be a space between the variable name and the equal sign, which may be inconsistent with All programming languages ​​you are familiar with are different. At the same time, the naming of variable names must follow the following rules:

  • The first character must be a letter (a-z, A-Z).

  • There cannot be spaces in the middle, and underscores (_) can be used.

  • Punctuation marks cannot be used.

  • Keywords in bash cannot be used (you can use the help command to view reserved keywords).

In addition to explicit direct assignment, you can also use statements to assign values ​​to variables, such as:

for file in `ls /etc`

The above statement will loop out the file names in the directory under /etc.


Using variables

To use a defined variable, just add a dollar sign in front of the variable name, such as:

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

The curly braces outside the variable name It is optional, you can add it or not. The curly braces are added to help the interpreter identify the boundaries of the variables, such as the following situation:

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, write echo "I am good at $skillScript", the interpreter will treat $skillScript as a variable (its value is empty), and the code execution result will not be what we expect.

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

Defined variables can be redefined, such as:

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

This is legal to write, but note that you cannot write $your_name="alibaba" when assigning a value for the second time. Use Only add the dollar sign ($) when specifying variables.

Read-only variable

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

The following example attempts to change a read-only variable, but an error is reported:

#!/bin/bash
myUrl="http://www.w3cschool.cc"
readonly myUrl
myUrl="http://www.php.cn"

Run the script, and the results are as follows:

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

Delete the variable

Use the unset command. Delete variables. Syntax:

unset variable_name

After a variable is deleted, it cannot be used again. The unset command cannot delete read-only variables.

Example

#!/bin/sh
myUrl="http://www.php.cn"
unset myUrl
echo $myUrl

There will be no output when the above example is executed.

Variable type

When running the shell, three variables will exist at the same time:

  • 1) Local variablesLocal variables are in Defined in a script or command, it is only valid in the current shell instance. Programs started by other shells cannot access local variables.

  • 2) Environment variablesAll programs, including programs started by the shell, can access environment variables. Some programs require environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.

  • #3) Shell variables Shell variables are special variables set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of the shell


Shell String

String is the most commonly used and useful data type in shell programming (except for numbers and strings, there are no other types that are easy to use) , the string can use single quotes, double quotes, or no quotes. The difference between single and double quotes is similar to PHP.

Single quotes

str='this is a string'

Restrictions on single quoted strings:

  • Any characters in single quotes will be output as they are, and variables in single quote strings are invalid;

  • Single quotes cannot appear in single-quoted strings (not even after using escape characters for single quotes).

Double quotes

your_name='qinjx'
str="Hello, I know your are \"$your_name\"! \n"

Advantages of double quotes:

  • You can have variables

  • in double quotes Escape characters can appear in double quotes

##Splicing strings

your_name="qinjx"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1

Getting the string length

string="abcd"
echo ${#string} #输出 4

Extracting substrings

The following example intercepts

4 characters starting from the 2 character in the string:

string="php is a great site"
echo ${string:1:4} # 输出 unoo

Find substring

Find the character "

i or s" position:

string="php is a great company"
echo `expr index "$string" is`  # 输出 8

Note: In the above script, "`" is a backtick, not a single quote "'", Don’t get it wrong.


Shell Array

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 subscripts of array elements are numbered starting from 0. To obtain elements in an array, use subscripts. The subscript can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.

Define array

In Shell, brackets are used to represent arrays, and array elements are separated by "space" symbols. The general form of 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 each component of the array separately:

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

may not be used Continuous subscripts, and there is no limit to the range of subscripts.

Read array

The general format for reading array element values ​​is:

${数组名[下标]}

For example:

valuen=${array_name[n]}

Use the @ symbol to get all the elements in the array Element, for example:

echo ${array_name[@]}

Get the length of the array

The method of getting the length of the array is the same as the method of getting the length of the string, for example:

# 取得数组元素的个数
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}


Shell Note

Lines starting with "#" are comments and will be ignored by the interpreter.

There are no multi-line comments in sh, you can only add a # sign to each line. It can only be like this:

#--------------------------------------------
# 这是一个注释
# author:php中文网
# site:www.php.cn
# slogan: php中文网
#--------------------------------------------
##### 用户配置区 开始 #####
#
#
# 这里可以添加脚本描述信息
# 
#
##### 用户配置区 结束  #####

What should I do if during the development process, I encounter a large section of code that needs to be temporarily commented, and then uncommented after a while?

It is too laborious to add a # symbol to each line. You can enclose the code to be commented in a pair of curly braces and define it as a function. If there is no place to call this function, this code will not be executed. , achieving the same effect as comments.