Shell script programming specification and variable summary

1. Shell script programming specification

1.1 Shell script application scenarios

  • Shell script (Shell Script) is a program file that saves the commands to be executed in a text file in order, and gives the file executable permissions to facilitate one-time execution. It is mainly convenient for administrators to set up or manage, and can be combined with Shell control statements to complete complex operations.
  • Generally used for repetitive operations, batch transaction processing, automated operation and maintenance, service status operation monitoring, timing task execution, etc.

1.2 Shell script programming specification

  • Shell script is a special application program, which is between the operating system kernel and the user. It acts as a "command interpreter". It is responsible for receiving and interpreting the operation instructions input by the user, and passing the operation to the kernel for execution and output Results of the.

1.2.1 Shell interpreter types

  • There are many types of interpreters, different shell scripts, internal commands, and command prompts will have some differences
cat /etc/shells  查看当前系统所支持的脚本种类
[root@localhost ~]# cat /etc/shells 
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

1.2.2 Shell script editing

[root@localhost opt]# vim first.sh  ## 脚本文件以.sh 结尾
 #!/bin/bash  ## Shell解释器的程序为/bin/bash
#注释
cd /boot
pwd
ls -lh vml*

1.2.3 Shell script execution

Three ways:

  • ./PATH## Absolutely can be relative to have executable X permissions
  • sh PATH## Execution permission is not required. It is generally recommended to keep the path unchanged after execution, and the environment has not changed.
  • source first.sh ## The path has changed, and its environment has changed,. xxx ## is equivalent to source
  • ./l path
以刚才创建的Shell脚本为例子
[root@localhost opt]# ll
总用量 8
-rw-r--r--.  1 root root   116 7月  15 17:19 first.sh      ## 目前的权限里面没有可执行权限
[root@localhost opt]# ./first.sh  
-bash: ./first.sh: 权限不够    ## 无法执行 权限不够
[root@localhost opt]# chmod +x first.sh  ## 添加可执行权限
[root@localhost opt]# ./first.sh 
/boot
-rwxr-xr-x. 1 root root 6.4M 6月  22 08:03 vmlinuz-0-rescue-313cef57612341d5972004b949f7ed03
-rwxr-xr-x. 1 root root 6.4M 11月  9 2018 vmlinuz-3.10.0-957.el7.x86_64
[root@localhost opt]#          ## 路径未发生变化
  • sh path way
[root@localhost opt]# sh first.sh     ## 
/boot
-rwxr-xr-x. 1 root root 6.4M 6月  22 08:03 vmlinuz-0-rescue-313cef57612341d5972004b949f7ed03
-rwxr-xr-x. 1 root root 6.4M 11月  9 2018 vmlinuz-3.10.0-957.el7.x86_64
[root@localhost opt]#        ## 所在位置未变化  环境未发生改变
  • source path
[root@localhost opt]# source first.sh    
/boot
-rwxr-xr-x. 1 root root 6.4M 6月  22 08:03 vmlinuz-0-rescue-313cef57612341d5972004b949f7ed03
-rwxr-xr-x. 1 root root 6.4M 11月  9 2018 vmlinuz-3.10.0-957.el7.x86_64
[root@localhost boot]#                      ##所在位置变化  环境发生改变
[root@localhost opt]# . first.sh 
/boot
-rwxr-xr-x. 1 root root 6.4M 6月  22 08:03 vmlinuz-0-rescue-313cef57612341d5972004b949f7ed03
-rwxr-xr-x. 1 root root 6.4M 11月  9 2018 vmlinuz-3.10.0-957.el7.x86_64
[root@localhost boot]#          ##所在位置变化  环境发生改变

1.2.4 Shell script output prompt information

  • echo "The current directory is located at:" ## Add double quotes to represent strings
[root@localhost opt]# vim first.sh 
echo “当前目录位于:”

1.2.5 Redirection and pipeline operation

  • Interactive hardware device
Types of Explanation Device file File description number Default device
Standard input Receive user input data from this device /dev/stdin 0 keyboard
Standard output Output data to the user through the device /dev/stdout 1 monitor
Standard error output Report execution error messages through this device /dev/stderr 2 monitor
  • Redirect operation
Types of Operator use
Redirect input < Read data from the specified file instead of inputting from the home keyboard
Redirect output > Save the output result to the specified file (overwrite the original content)
Redirect output > > Append the output to the end of the specified file
Standard error output 2> Save the error information to the specified file (overwrite the original content)
Standard error output 2>> Append the error information to the specified file
Mixed output &> Save the contents of standard output and standard error to the same file
  • Output error information
[root@localhost ~]# cat  abc.txt 2> error.txt   
[root@localhost ~]#  cat error.txt 
cat: abc.txt: 没有那个文件或目录

  • Mixed output
## 不知道结果对的还是错的的时候用
[root@localhost ~]# cat  abc.txt  &>error01.txt   
[root@localhost ~]# cat error01.txt 
cat: abc.txt: 没有那个文件或目录

  • Don't want to see the output information:
[root@localhost ~]# yum install httpd  -y &> /dev/null      ## 将屏幕当中输出的信息导入到黑洞

Pipe operation symbol "|"

  • Use the output result of the command on the left as the processing target of the command on the right
[root@localhost ~]# grep "bash$" /etc/passwd | awk -F: '{print $1,$7}'
root /bin/bash          
wang /bin/bash
kgc /bin/bash
bdqn /bin/bash
tom /bin/bash
lisi /bin/bash

  • awk: regular expression, one of the three swordsmen to deal with the column
    -F: composition separator with a colon (F followed by a delimited symbol) write nothing The default is separated by tabs and spaces (-F does not write)
    print output
    $ position# # Separate with a comma

Two, variables

  • Shell variables are used to store specific parameters (values) required by the system and users. These parameters can be changed according to user settings or system changes. The values ​​of variables are stored in memory.
  • Function:
    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 (PATH)
    variable value: Can be changed according to user settings and changes in system environment
  • Variable type:
    custom variables: defined, modified and used by the user.
    Special variables, read-only variables, positional variables, and predefined variables ($?)

2.1 Define new variables

  • Variable names start with a letter or underscore, and are case sensitive, all uppercase is recommended
  • Basic format
    variable name = variable value (variable name on the left, variable value on the right, "=" is the assignment symbol)
[root@localhost ~]# name=zhangsan ## 把张三赋值给name

2.2 View and reference variable values

  • Add the symbol "$" before the variable name, you can refer to the value of a variable
  • You can use the echo command to view variables, and you can view multiple variable values ​​in a single echo command.
[root@localhost ~]# name=zhangsan
[root@localhost ~]# name1=wangwu
[root@localhost ~]# echo $name $name1
zhangsan wangwu

2.3 Special operations of variable assignment

  • Specifying the assignment content after the "=" is the most basic way to assign a value to a variable, and there are some operations that can assign a value to a variable more flexibly.

2.3.1 Double quotes (")

  • It is mainly used to define the character string, especially when the assignment content contains spaces, it must be enclosed in double quotes.
  • Allow reference to other variables through the $ symbol
[root@localhost ~]# abc=a b c   ## 包含空格 无法赋值
-bash: b: 未找到命令
[root@localhost ~]# abc="a b c" ## 赋值成功
[root@localhost ~]# echo $abc
a b c

2.3.2 Single quote (')

  • When the content to be assigned contains characters with special meaning such as "$" "" "" \", it should be enclosed in single quotation marks.
  • Within the range of single quotation marks, the values ​​of other variables cannot be quoted. Any character is treated as a normal character, but the assignment contains single quotation marks, which need to be escaped with ",".
[root@localhost ~]# abc='$abc'
[root@localhost ~]# echo $abc 
$abc
[root@localhost ~]# abc=ab\'c  ## 辅助内容中有单引号
[root@localhost ~]# echo $abc 
ab'c

2.3.3 Backtick (`)

  • Mainly used for command substitution, allowing the 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.
[root@localhost ~]#  num3=`ps aux | wc -l`  ## 将进程数赋值给num3
[root@localhost ~]# echo $num3
126
  • When it is difficult to implement nested command operations in a line of commands using back apostrophes, you can use "$()" instead of back apostrophe operations.
[root@localhost ~]# rpm -qc $(rpm -qf $(which useradd)) ## 查询提供useradd命令程序的软件包所安装的位置
/etc/default/useradd
/etc/login.defs

2.3.4 read command

  • It is a built-in command of bash. The read command is used to prompt the user to enter information, so as to implement a simple interaction process.
  • When executing, it will read a line of content from the standard input device (keyboard), and use the space as a separator to assign each read field to the specified variable one by one (the extra content is assigned to the last one), and there is only one specified variable. The entire line of content is assigned to this variable.
[root@localhost ~]# read num
1
[root@localhost ~]# read num1 num2
1 2
[root@localhost ~]# echo $num $num1 $num2
1 1 2

  • The read command can be combined with "-p" and "-t" to set prompt information and input waiting time
[root@localhost opt]# vim first.sh 
read  -p "请输入一个数值:" sum
echo "你输入的值是:$sum"
[root@localhost opt]# sh first.sh 
请输入一个数值:1
你输入的值是:1

Three, 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 subprogram or a new child Shell script, the variables defined in the parent Shell environment cannot be referenced.
[root@localhost ~]# echo $num
1
[root@localhost ~]# bash  ## 进入子shell环境
[root@localhost ~]# echo $num  ## 环境改变无法调用

[root@localhost ~]# 

3.1 Global variables

  • Variables defined by global variables can continue to be used in all sub-Shell environments, and the specified variables can be exported as global variables through the internal command Export
  • System: /etc/profile for the entire user
  • User variables: ~/.bash_profile
[root@localhost ~]# num2=2
[root@localhost ~]# export num2  ## 将num2指定为全局变量
[root@localhost ~]# bash ## 进入子Shell环境
[root@localhost ~]# echo $num2   ## 调用成功
2

  • It is also possible to assign values ​​to variables when global variables are everywhere.
[root@localhost ~]# export num3=3

Fourth, the calculation of numerical variables

  • Numerical operations of shell variables are mostly used for script process control (such as cycle times, usage comparison, etc.).
  • 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, the basic format is as follows
基本格式:
expr  变量1 运算符 变量2 [运算符 变量3]………… ## 变量为对应需要计算的数值(需以"$"符号调用)
Operator significance
++ – Increase and decrease, can be placed at the front or at the end
\* / % Multiplication, division, remainder
+ - Addition, subtraction
< <= > >= Comparison symbol
== ! = Equal and not equal
& Bitwise and
^ XOR
| Bitwise or
&& Logical and
|| Logical OR
?: Conditional expression
= += -= *= /= %= &= ^= <<= >>= |= Assignment operation a+=1 is equivalent to a=a+1
  • Calculation example
[root@localhost ~]# a=2
[root@localhost ~]# b=3
[root@localhost ~]# expr $a + $b
5
[root@localhost ~]# expr $a \* $b
6
[root@localhost ~]# expr $b \% $a
1

  • Assign the result of the operation to other variables using a backtick
[root@localhost ~]# num5=`expr $a \* $b \* $a`
[root@localhost ~]# echo $num5
12
  • In addition to expr variable values, common commands include (()), let, etc. If you want to perform a simple operation, just enclose the specific arithmetic expression with "$((" and "))".
[root@localhost ~]# bb=$((1+2**3-4)) ## 算法为 1+2的三次方-4
[root@localhost ~]# echo $bb
5

Five, special scalar

5.1 Environment variables

  • Environment variables refer to a type of variables created in advance by the Linux system for operational needs, and 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. Common environment variables are:
    USER: indicates the user name
    HOME: indicates the user's home directory.
    LANG: indicates the language and character set
    PWD: indicates the current working directory
    PATH: indicates the command search path.
[root@localhost ~]# env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
PWD=/root
LANG=zh_CN.UTF-8
SELINUX_LEVEL_REQUESTED=
HISTCONTROL=ignoredups
SHLVL=1
HOME=/root
LOGNAME=root	
  • PATH is used to run and set the default search path of executable programs. When specifying the file name to execute the command program, the linux program will search for the corresponding executable file in the directory range specified by the PATH variable.
[root@localhost ~]# ls -lh /root/caiquan.sh   ## 查看脚本位置
-rwxr-xr-x. 1 root root 1.4K 7月  17 08:55 /root/caiquan.sh      
[root@localhost ~]# PATH="$PATH:/root"    ## 将root添加到搜索路径
[root@localhost ~]# caiquan.sh    ## 可以直接以文件名运行脚本
请输入您的出拳手势 其中  0代表拳头 1代表剪刀 2代表布 0
您出的是拳头
电脑出的是布
您输了,电脑赢了!
  • In the Linux system, the global configuration file of environment variables is /etc/profile, and the variables defined in this file are used for all users.
  • Each user has its own independent profile (~/.bash_profile).

5.2 Location variables

  • When using a linux script program, it is convenient to provide operating parameters for the program through the command line. Bash introduces the concept of location variables.
  • When executing command line operations, the first field represents the name of the command or script program, and the remaining strings 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, $4, $5, $6, and $7.
[root@localhost ~]# vim adder2num.sh
#! /bin/bash
SUM=`expr $1 + $2`
echo "$1+$2 = $SUM"
[root@localhost ~]# ./adder2num.sh 52 38
52+38 = 90 

5.3 Predefined variables

  • Predefined variables are a type of variables that are predefined by the Bash program. Users can only use predefined variables, but cannot create new predefined variables, nor can they directly assign values ​​to predefined variables.
$#:表示命令行中位置参数的个数。
$*:表示所有位置参数的内容。
$?:表示前一条命令执行后的返回状态,返回值为0表示执行正常,返回非0值表示表示执行出现异常。
$0:表示当前执行的脚本或程序的名称。

Guess you like

Origin blog.csdn.net/weixin_47219725/article/details/107371890