The role and type of variables in Shell programming

1. The role and type of Shell variables

The concept of "variables" is used in various Shell environments. Shell variables are used to store specific parameters (values) that the system and users need to use, and these parameters can be changed according to user settings or changes in the system environment. By using variables, the Shell program can provide more flexible functions and more adaptable.
The types of common shell variables include custom variables, environment variables, read-only variables, location variables, and predefined variables .

Two, custom variables

Custom variables are variables defined by system users themselves, which are only valid in the user's own Shell environment, so they are also called local variables. When writing a Shell script program, some specific custom variables are usually set to adapt to various changes during the execution of the program and meet different needs.

1. Define new variables

Variable operations in Bash are relatively simple, not as complicated as other high-level programming languages ​​(such as C/C++, Java, etc.). When defining a new variable, you generally do not need to declare it in advance, but directly specify the variable name and assign it to the initial value (content). The basic format for defining variables is "variable name=variable value" with no spaces on either side of the equal sign. The variable name should start with a letter or underscore, and the name should not contain special characters (such as +, -, *, /, .,?, %, &, #, etc.).

For example, to define a variable named "Product" (value Python) and a variable named "Version" (value 2.7.13), you can do the following.

[root@localhost ~]# Product=Python
[root@localhost ~]# Version=2.7.13
2. View and reference the value of the variable

By adding the leading symbol "$" before the variable name, you can refer to the value of a variable. Use the echo command to view variables, and you can view multiple variable values ​​in one echo command.

[root@localhost ~]# echo $Product
Python
[root@localhost ~]# echo $Product $Version
Python 2.7.13

When the variable name is easily confused with other characters that follow it, you need to add braces "{}" to enclose it, otherwise the correct variable name cannot be determined. For undefined variables, it will show a null value.

[root@localhost ~]# echo $Product2.5	//变量Product2.5 并未定义
.5
[root@localhost ~]# echo ${Product}2.5
Python2.5
3. Special operation of variable assignment

Specifying the content of the variable directly after the equal sign "=" is the most basic way to assign a value to a variable. In addition, there are some special assignment operations, which can assign values ​​to variables more flexibly, so as to be suitable for various complex management tasks. .
(1) Double quotation marks (")
Double quotation marks mainly play a role in delimiting strings, especially when the content to be assigned contains spaces, it must be enclosed in double quotation marks; in other cases, double quotation marks can usually be omitted.

For example, if you want to assign Python 2.7.13 to the variable PYTHON, you should perform the operation PYTHON="Python 2.7.13".

[root@localhost ~]# PYTHON=Python 2.7.13 	//错误的赋值
bash: 2.7.13: command not found
[root@localhost ~]# PYTHON="Python 2.7.13"	//正确的赋值
[root@localhost ~]# echo $PYTHON
Python 2.7.13

Within the range of double quotation marks, the value of other variables (variable references) can be quoted using the " $ " symbol, so that the value of an existing variable can be directly called to assign a new variable.

For example, perform the following operations to call the value of the variable Version and assign it to a new variable PyVersion, the final value is "Python 2.7.13".

[root@localhost ~]# PyVersion="Python $Version"	//以变量的值进行赋值
[root@localhost ~]# echo $PyVersion
Python 2.7.13

(2) Single quotation mark (')
When the content to be assigned contains special meaning characters such as $, ", \, etc., it should be enclosed in single quotation marks. Within the scope of single quotation marks, the values ​​of other variables cannot be quoted , Any character is treated as a normal character. However, when the assignment contains a single quotation mark ('), it must be escaped with the \'symbol to avoid conflict.

[root@localhost ~]# PyVersion='Python $Version'       //$符号不能再引用变量
[root@localhost ~]# echo $PyVersion 	             //原样输出字符串
Python $Version

(3) Backtick (`)
Backtick is mainly used for command substitution, allowing the screen output result of executing a command to be assigned to a variable. The range enclosed by the backtick must be an executable command line, otherwise an error will occur.

For example, if you want to find the location of the useradd command program in a line of commands and list its detailed attributes, you can perform the following operations.

[root@localhost ~]# ls -lh `which useradd`
-rwxr-x---. 1 root root 101K 8 月 2 2011 /usr/sbin/useradd

The above operation is equivalent to executing two commands consecutively-first find out the program location of the useradd command through the which useradd command, and then list the file attributes according to the search result. During the execution, the output of the which useradd command will replace the entire backtick range.

To extract the log-in prohibited user list of the vsftpd service and assign it to the variable DenyList, you can perform the following operations.

[root@localhost ~]# DenyList=`grep -v "^#" /etc/vsftpd/ftpusers`
[root@localhost ~]# echo $DenyList
root bin daemon adm lp sync shutdown halt mail news uucp operator games nobody

It should be noted that it is difficult to implement nested command substitution operations in a line of commands using back apostrophes. At this time, you can use " $() " instead of back apostrophes to solve the nesting problem.

For example, if you want to query the location of the configuration file installed by the software package that provides the useradd command program, you can perform the following operations (replace in order from the inside out).

[root@localhost ~]# rpm -qc $(rpm -qf $(which useradd))
/etc/default/useradd
/etc/login.defs

(4), read command
In addition to the above assignment operations, you can also use Bash's built-in command read to assign values ​​to variables. The read command is used to prompt the user to input information, so as to realize a simple interaction process. During execution, a line of content will be read from the standard input device (keyboard), with spaces as the separator, and each field read will be assigned to the specified variable in turn (the extra content is assigned to the last variable). If there is only one variable specified, the entire line will be assigned to this variable.
For example, performing the following operation will wait for the user to enter text and assign the entered content to the variable ToDir1.

[root@localhost ~]# read ToDir1
/opt/backup/	//输入变量ToDir1 的值为/opt/backup/ [root@localhost ~]# echo $ToDir1
/opt/backup/

In order to make the interactive operation interface more friendly and improve ease of use, the read command can be combined with the "-p" option to set prompt information to inform the user what should be input and other related matters.

For example, if you want to prompt the user to enter the storage directory of the backup file and assign the entered path information to the variable ToDir2, you can perform the following operations.

[root@localhost ~]# read -p "请指定备份存放目录:" ToDir2
请指定备份存放目录:/opt/backup
[root@localhost ~]# echo $ToDir2
/opt/backup
4. Set the scope of the variable

By default, newly defined variables are only valid in the current Shell environment, so they are called local variables. When entering a subroutine or a new subshell environment, local variables can no longer be used.

For example, after directly executing Bash to enter a new child Shell script, it will not be possible to reference the Product, Version and other variables defined in the parent Shell environment.

[root@localhost ~]# echo "$Product $Version"	//查看当前定义的变量值Python 2.7.13
[root@localhost ~]# bash	//进入子Shell 环境
[root@localhost ~]# echo "$Product $Version" //无法调用父Shell 环境中的变量
[root@localhost ~]# exit                    //返回原有的Shell 环境

In order to enable user-defined variables to continue to be used in all sub-Shell environments and reduce repeated settings, the specified variables can be exported as global variables through the internal command export. The user can specify multiple variable names as parameters at the same time (without using the "$" symbol), and the variable names are separated by spaces.

[root@localhost ~]# echo "$Product $Version"	//查看当前定义的变量值Python 2.7.13
[root@localhost ~]# export Product Version	   //将Product、Version 设为全局变量
[root@localhost ~]# bash	                 //进入子Shell 环境
[root@localhost ~]# echo "$Product $Version"
Python 2.7.13	                           //可以调用父Shell 的全局变量
[root@localhost ~]# exit	              //返回原有的Shell 环境

While using export to export global variables, you can also assign values ​​to variables, so you don't need to assign values ​​in advance when you newly define global variables.

For example, perform the following operations to directly create a new global variable named FQDN.

[root@localhost ~]# export FQDN="www.jb-aptech.com.cn"
[root@localhost ~]# echo $FQDN
www.jb-aptech.com.cn
5. Operation of Numerical Variables

Numerical operations of shell variables are mostly used for process control of script programs (such as cycle times, usage comparison, etc., which will be introduced in subsequent chapters). In the Bash Shell environment, only simple integer operations can be performed, and decimal operations are not supported. The calculation of integer value is mainly carried out through the internal command expr, and the basic format is shown below. Note that there must be at least one space between the operator and the variable.
expr variable 1 operator variable 2 [operator variable 3]...
Among them, variable 1, variable 2... correspond to the numerical variable that needs to be calculated (need to be called with the "$" symbol). Several commonly used operators are described below.

  • +: Addition operation.
  • -: Subtraction operation.
  • *: Multiplication operation. Note that you cannot use only the "*" symbol, otherwise it will be regarded as a file wildcard.
  • /: Division operation.
  • %: Modulo operation, also known as remainder operation, used to calculate the remainder after dividing a value.
    For example, two variables X (value 35) and Y (value 16) are set, and the results of addition, subtraction, multiplication, division and modulo operation of variables X and Y are demonstrated in turn.
[root@localhost ~]# X=35 
[root@localhost ~]# Y=16
 [root@localhost ~]# expr $X + $Y 51
[root@localhost ~]# expr $X - $Y
19
[root@localhost ~]# expr $X \* $Y
560
[root@localhost ~]# expr $X / $Y
2
[root@localhost ~]# expr $X % $Y
3

If you want to assign the result of the operation to other variables, you can combine the command substitution operation (using the backtick).

For example, calculate the 3rd power of the variable Y and assign the result to the variable Ycube.

[root@localhost ~]# Ycube=`expr $Y \* $Y \* $Y`
[root@localhost ~]# echo $Ycube
4096

Three, special shell variables

In addition to user-defined Shell variables, there are also a series of special variables in the Linux system and Bash Shell environment- environment variables, read-only variables, location variables, and predefined variables.

1. Environment variables

Environment variables refer to a type of variables created in advance by the Linux system for operational needs. They are mainly used to set the user's working environment, including user home directory, command search path, user current directory, login terminal, etc. The values ​​of environment variables are automatically maintained by the Linux system and will change as the user's status changes. Use the env command to view the environment variables in the current working environment. For some common environment variables, you should understand their respective uses.

For example, the variable USER represents the user name, HOME represents the user's home directory, LANG represents the language and character set, PWD represents the current working directory, PATH represents the command search path, etc.

[root@localhost ~]# env	//选取部分内容
XDG_SESSION_ID=135
HOSTNAME=localhost.localdomain 
…… //省略部分内容

The PATH variable is used to set the default search path of the executable program. When only the file name is specified to execute the command program, the Linux system will search for the corresponding executable file in the directory specified by the PATH variable. If it cannot find it, it will prompt "command not found".

For example, the first.sh script is located in the /root directory. If you want to run the script directly by the file name, you can modify the PATH variable to add the search path, or copy the first.sh script to a folder in the existing search path under.

[root@localhost ~]# vim frist.sh
#!/bin/bash
#一个简单的Shell脚本        //“#”用于注释的内容
cd/opt/                                    //切换到opt目录
echo "当前位于哪个目录:"    //在屏幕显示“ ....... ”
pwd                                          //查看当前在那个目录中
echo "查看当前目录:"      
ls -lh 
[root@localhost ~]# chmod +x first.sh       //为脚本增加执行权限
[root@localhost ~]# ls -lh /root/first.sh	//确认脚本位置
-rwxr-xr-x. 1 root root 27 Jul 4 09:24 /root/first.sh
[root@localhost ~]# echo $PATH	//查看当前搜索路径
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/mysql/bin:/root/bin 
[root@localhost ~]# first.sh	//直接执行时找不到命令
-bash: first.sh: command not found
[root@localhost ~]# PATH="$PATH:/root"	//将/root 添加到搜索路径
[root@localhost ~]# echo $PATH	//查看修改后的搜索路径
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/mysql/bin:/root/bin:/root 
[root@localhost ~]# first.sh	//直接以文件名运行脚本
当前位于哪个目录:
/opt
........... //省略部分内容
2. Read-only variables

There is a special case in Shell variables. Once set, their value cannot be changed. Such variables are called read-only variables. When creating a variable, you can set it as a read-only attribute, or you can set an existing variable as a read-only attribute. Read-only variables are mainly used when the value of the variable is not allowed to be modified.

For example, a variable "log_path" is defined in the script to define the path of the log file. If you don't want to be modified during the execution of the script, you can set this variable as a read-only variable. Use the readonly command to define a variable as a read-only variable, and it cannot be modified by re-assignment after the definition.

[root@localhost ~]# name=cloud
[root@localhost ~]# readonly name	//设置为只读变量
[root@localhost ~]# echo $name
cloud
[root@localhost ~]# name=yun
-bash: name: readonly variable	//只读变量不可以被重新赋值
[root@localhost ~]# unset name	//只读变量不可以被删除
//上述 unset 命令通常用于删除变量。
-bash: unset: name: cannot unset: readonly variable
3. Location variables

In order to provide operating parameters for the program through the command line when using Shell script programs, Bash introduces the concept of positional variables. When executing command line operations, the first field represents the name of the command or script program, and the remaining string parameters are assigned to the positional variables in order from left to right. Positional variables are also called positional parameters and are represented by $1, $2, $3, ..., $9.

For example, when the command line "ls -lh/boot/" is executed, the first position variable is "-lh", which is represented by "$1"; the second position variable is "/boot/", which is represented by "$2" Said. The name of the command "ls -lh/boot/" or the script itself is represented by "$0". Although the format of $0 is the same as that of a positional variable, $0 is a predefined variable instead of a positional variable.

[root@localhost ~]# vim jf.sh     
#!/bin/bash 
SUM=`expr $1 + $2`                //声明脚本算法
echo "$1 + $2 = $SUM"             //打印到屏幕上
[root@localhost ~]# chmod +x jf.sh   //为脚本增加执行权限
[root@localhost ~]# ./jf.sh 12 34	//$1 为 12、$2 为 34 的情况
12 + 34 = 46
[root@localhost ~]# ./jf.sh 56 78	//$1 为 56、$2 为 78 的情况
56 + 78 = 134
4. Predefined variables

Pre-defined variables are a type of special variables that are predefined by the Bash program. Users can only use pre-defined variables, but cannot create new ones, nor can they directly assign values ​​to pre-defined variables. Pre-defined variables are represented by a combination of the "$" symbol and another symbol. The meanings of several commonly used pre-defined variables are as follows.

  • $#: Represents the number of positional parameters in the command line.
  • $*: indicates the content of all positional parameters.
  • $ ?: Indicates the return status after the previous command is executed. A return value of 0 indicates that the execution is correct. Any return value other than 0 indicates that the execution is abnormal. The use of the $? Variable will be introduced in the next chapter.
  • $0: Represents the name of the currently executing script or program.

In order to illustrate the role of the predefined variables, a small script for the backup operation is written below to package and compress multiple files or directories specified by the command line and output related information. Among them, the UNIX timestamp (the number of seconds that have elapsed since January 1, 1970) is embedded in the name of the newly created compressed file, and it is obtained through the "date +%s" command.

[root@localhost ~]# vim mybak.sh
#!/bin/bash
TARFILE=beifen-`date +%s`.tgz   //声明变量引用时间戳
tar zcf $TARFILE $* &> /dev/null    /将备份的文件压缩命名
echo "已执行 $0 脚本,"
echo "共完成 $# 个对象的备份" 
echo "具体内容包括: $*"
[root@localhost ~]# chmod +x mybak.sh
[root@localhost ~]# ./mybak.sh /boot/grub       //备份一个对象的情况
已执行 ./mybak.sh 脚本,
共完成 1 个对象的备份
具体包括:/boot/grub
[root@localhost ~]# ./mybak.sh /etc/passwd /etc/shadow     //备份两个对象的情况
已执行 ./mybak.sh 脚本, 
共完成 2 个对象的备份
具体包括:/etc/passwd /etc/shadow
[root@localhost ~]# ls -lh beifen-*	          //确认备份结果
-rw-r--r--. 1 root root 368 Jul 4 09:37 beifen-1499175456.tgz
-rw-r--r--. 1 root root 1.8K Jul 4 09:37 beifen-1499175464.tgz

Guess you like

Origin blog.csdn.net/wulimingde/article/details/108071594