Shell script programming specifications and variables (the rules that shell scripts must know!)

Shell script programming specifications and variables


Shell is a special application program, it is between the operating system kernel and the user, acting as a "command interpreter", responsible for receiving and interpreting the operating instructions (commands) entered by the user, and passing the operations that need to be performed Give the kernel execution and output the execution result. Bash (/bin/bash) is the default shell used by most Linux versions.

1. Shell script overview

1. The concept of Shell script

1) Save the order of the commands to be executed to a text file
2) Give the file executable permission to run
3) Combine various Shell control statements to complete more complex operations

2. Application scenarios of Shell scripts

1) Repetitive operations
2) Batch transaction processing
3) Automated operation and maintenance
4) Service running status monitoring
5) Timing task execution

3. The role of Shell

1) Shell is the command interpretation tube, the "translator" between the user and the kernel, responsible for interpreting the command line input by the user.

Insert picture description here

2) User login Shell

  • ShellI program used by default after login, generally /bin/bash
  • The internal instructions and operating environment of different Shells will be different
[root@localhost ~]# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
....

Insert picture description here

Two, write a shell script

1. Write script code

●Using the vim text editor,
one Linux command per line, written in order of execution

[root@localhost ~]#vim first.sh #编辑脚本文件,以.sh结尾是方便识别出这是个shell脚本文件
cd /boot/ #切换到根目录
pwd  #查看当前所在目录
ls -lh vml* #以长格式更人性化的方式显示以vml开头的文件

Insert picture description here

The above first.sh script file includes three commands: cd /boot/, pwd, ls -lh vml*. After executing this script file, the output result is actually the result of executing these three commands in sequence, thus realizing "batch processing".

2. Grant executable permissions

● Make the script executable

[root@localhost~]#chmod +x first.sh

Insert picture description here

3. Execute the script file

1) Method 1: The command to specify the path requires the file to have x permission. (Absolute path and relative path)

chmod +x /root/first.sh

Specify the absolute path: /root/first.sh

Insert picture description here

Specify relative path: ./first.sh

Insert picture description here

2) Method 2: Specify Shell to interpret the script, and the file does not require x permission.

sh script path: sh first.sh or sh /root/first.sh

Relative path (need to be in the directory where the script is located), this script is originally created in the home directory (~ directory), root's home directory is root.

Insert picture description here

Absolute path (specify the specific path of the file directly)

Insert picture description here

3) Method three: source script path or. Script path (x permission is not required)

. first.sh or source first.sh (same as above for path requirements)

Insert picture description here

This execution method will automatically switch to the boot directory. This is because source and. Read the configuration of the script directly in the current process, and will not start a new process!
Source will run the content of the script directly to the parent process (because it does not open up a new process, it can be said that it directly adds the execution content of the script to the current process). So after you source, the variables configured inside will be added to the current environment, and you can call the variables in the script in the shell!
And ./first.sh and sh first.sh
are a new sub-shell process to run this script under the current process. When the script is finished, the variables set in sh and the sub-process are destroyed together! (The child shell inherits the environment variables of the parent process shell, and the variables will be destroyed when the child shell ends. If export is used, the variables of the child shell can be fed back to the parent-level shell).

4. More complete script composition

  • Script statement
  • Annotation information
  • Executable statement
[root@localhost~]#vim /first.sh
#!/bin/bash 
#This is my first Shell-Script. 
cd /boot
echo "当前的目录位于∶" 
pwd
echo "其中以vml开头的文件包括∶"   #输出友好提示信息
ls -Ih vml*

Insert picture description here

In the above first.sh script file, the first line "#!/bin/bash" is a special script statement, indicating that the statements after this line are interpreted and executed by the /bin/bash program; other statements beginning with "#" Indicates comment information; the echo command is used to output strings to make the output information of the script easier to read. For example, if the rewritten first.sh script is executed, the output result is as follows.

Insert picture description here

Fourth, redirection and pipeline operation

1. Interactive hardware equipment

  • Standard Input: Receive user input data from the device
  • Standard output: output data to the user through the device
  • Standard error: report execution error information through this device
Types of Device file File description number Default device
Standard input /dev/stdin 0 keyboard
Standard output /dev/stdout 1 monitor
Standard error output /dev/stderr 2 monitor

2. Redirection operation

Types of Operator use
Redirect input < Read data from the specified file
Redirect output > Save the standard output result to the specified file, and overwrite the original content
Redirect output >> Append the standard output result to the end of the specified file without overwriting the original content
Standard error output 2> Save the error information to the specified file and overwrite the original content
Standard error output 2>> Append the error message to the end of the specified file without overwriting the original content
Mixed output &> Save standard output and standard error to the same file
Mixed output 2>&1 Redirect standard error output to standard output

For Example:

vim passwd.txt
222222
echo "123456" > passwd.txt
echo "123456" >> passwd.txt

Use> to output the content to the file, which will directly overwrite the file content

Insert picture description here

Insert picture description here

Use >> to indicate append to the file, it will start a new line

Insert picture description here

setenforce 0
echo "123456" > passwd.txt
passwd --stdin zs < passwd.txt

Insert picture description here

Obtain the password from the pass.txt file. Note that SELinux will affect the execution of the command. If the execution fails, you can try to close it and try again.

3. Pipe operation symbol "|"

The output result of the command on the left is used as the input (processing object) of the command on the right. Multiple pipes can be used in the same command line.

For Example:

ps aux | wc -l #显示所有进程数

Insert picture description here

echo "abc123" | passwd --stdin zs #更改用户zs的密码为abc123

Insert picture description here

Five, the role and type of Shell variables

Variables are values ​​that will change, and those that will not change are constants

1. The role of variables

Used to store specific parameters (values)
that the system and users need to use. Variable name: use a fixed name, preset by the system or user-defined.
Variable value: can change according to user settings and changes in the system environment

2. Types of variables

Custom variables: defined, modified and used by the user.
Special variables: environment variables, read-only variables, location variables, predefined variables

3. Custom variables

Define a new variable

变量名=变量值    #变量名以字母或下划线开头,区分大小写,建议全大写

View the value of a variable

echo $变量名 #查看当前变量的值

Note: There can be no spaces on both sides of "=" when assigning a value

For Example:

Insert picture description here

4. Use quotation marks when assigning values

Double quotation marks: Allow to quote other variable values ​​through the $ symbol

Single quotes: It is forbidden to quote other variable values, and $ is treated as a normal character

Backtick: command replacement, extract the output after the command is executed, `` has the same effect as $(...)

Insert picture description here

5. Input content from the keyboard to assign values ​​to variables

The read command gets the input

read -p 提示信息 变量名
echo $变量名

Insert picture description here

It can also be used in scripts to collect information.

For Example:

Insert picture description here

After granting the script execution permission, the execution result is as follows

Insert picture description here

6. The scope of the variable

1) 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 sub-Shell environment, local variables can no longer be used.

2) The specified variables can be exported as global variables through the internal command export, so that user-defined variables can continue to be used in all sub-Shell environments.

  • Set the scope expression of the variable:
格式1:export 变量名
格式2:export 变量名=变量值

You can use the pstree command to view the Shell environment, enter the bash command to enter the sub-Shell environment, press the Ctrl+D key combination or enter the exit command to exit the sub-Shell environment.

Insert picture description here

Enter bash to enter the sub-bash environment (also called the sub-Shell environment), which is equivalent to opening a sub-process.

Insert picture description here

After assigning a value to PRODUCT in the current parent bash environment, I entered the sub-environment and found that the variable value of PRODUCT could not be viewed in the sub-environment because PRODUCT is not a global environment variable, and the PRODUCT in the sub-environment has not been assigned. After outputting PRODUCT as a global environment variable, you can still view the variable value of the parent environment variable PRODUCT even if you enter the child Shell environment.

Insert picture description here

7. Operation of integer variables

  • Operation expression
格式:expr 变量1 运算符 变量2 [运算符 变量3]
  • Common operators

Addition +, subtraction -, multiplication \*, division /, take the remainder %.

Commonly used arithmetic expressions:

a=`expr 11 \* 2`
echo $((10 / (1+1)))
echo $[10 / (1+1)]
let i=12*4

i++ 相当于 i=$[$i+1]
i-- 相当于 i=$[$i-1]
i+=2 相当于 i=$[$i+2]

Insert picture description here

Six, special shell variables

1. Environment variables

Created in advance by the system to set the user’s working environment.
Configuration files: /etc/profile (globally effective), ~/.bash_profile (current user environment)

2. Common environment variables

PWD、PATH
USER、SHELL、HOME

Use the env command to view the environment variables in the current working environment. 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, and the variable PATH represents the default search for executable programs. path

3.PATH (path environment variable)

echo $PATH					#查看当前搜索路径
PATH="$PATH:/root"			#将/root目录添加到搜索路径
export PATH="$PATH:/root"	#输出为全局环境变量
first.sh

Insert picture description here

Switching to the sub-Shell environment is still executable, and other directories are still executable

Insert picture description here

4. Read-only variables

Used when the variable value is not allowed to be modified

readonly 命令设置只读变量
readonly PRODUCT				#设置为只读变量
echo $PRODUCT
PRODUCT=Python			        #只读变量不可以被重新赋值
unset PRODUCT					#只读变量不可以被删除,unset 命令用于删除变量,但无法删除只读变量,只能重启系统解决

Insert picture description here

5. Location variables

Execute the script sh xxx.sh 1 2 3 4 5 6 7 8 9 10…n

$n: n is a number, $0 represents the command itself, 1~9 represent the first to ninth parameters, parameters above ten need to be expressed in braces, for example, the tenth parameter is ${10}

Insert picture description here

6. Predefined variables

$*、$@:表示命令或脚本要处理的参数。
  $*:把所有参数看成以空格分隔的一个字符串整体,代表"$1 $2 $3 $4"。
  $@:把各个参数加上双引号分隔成n份的参数列表,每个参数是独立  的,代表"$1" "$2" "$3" "$4"。

$0:表示当前执行的脚本或命令的名称。
$#:表示命令或脚本要处理的参数的个数。	
$?:表示前一条命令或脚本执行后的返回状态码,返回值为0表示执行正确,返回任何非0值均表示执行出现异常。
也常被用于Shell脚本中return退出函数并返回的退出值。
[root@localhost ~]#echo `date +%F` #查看完整日期,按照年-月-日的格式输出
2020-12-20
[root@localhost ~]#vim mybak.sh #编辑脚本
#!/bin/bash            #表示此行以后的语句通过/bin/bash程序来解释执行
time=backup-`date +%F`.tar.gz #把变量值backup-`date+%F`.tar.gz赋值给变量time
tar zcf $time $* &> /dev/null	#/dev/null表示的是一个黑洞文件,通常用于丢弃不需要的数据输出。
echo "已执行 $0 脚本,"
echo "共完成 $# 个对象的备份"
echo "具体内容包括: $*"

[root@localhost ~]#chmod +x mybak.sh #赋予执行权限
[root@localhost ~]#./mybak.sh /etc/passwd /etc/shadow

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35456705/article/details/111873256