Shell programming specifications and variables (detailed graphic interpretation)

Shell programming specifications and variables

1. Shell script overview

(1) The concept of Shell script

Save the commands to be executed to a text file in order,
give the file executable permissions,
and combine various Shell control statements to complete more complex operations

vim first.sh #写一个first.sh的脚本文件

Insert picture description here
Insert picture description here

(Two), Shell script application scenarios

Repetitive operations
Interactive tasks
Batch transaction processing
Service running status monitoring
Timing task execution
...

(3) The role of Shell-command interpreter, "translator"

The shell 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 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.

Insert picture description here

1. The user's login shell

Bash (/bin/bash) is the default shell used by most Linux versions.

The internal instructions and operating environment of different Shells will be different

Insert picture description here

(4) Write the first Shell script

1. The composition of the Shell script

1. Script statement (interpreter): If the first line is "#!/bin/bash", it means that the code statements below this line are interpreted and executed by the /bin/bash program, and #!/bin/bash is the default interpreter . There are other types of interpreters, such as #!/usr/bin/python, #!/usr/bin/expect.

2. Comment information: The sentence beginning with "#" is expressed as comment information, and the commented sentence will not be executed when the script is run.

3. Executable statements: such as echo command, used to output the string between ""

vim /root/first.sh
#!/bin/bash
echo "hello world"

2. Execution of Shell script

Method 1: The command to specify the path requires the file to have x permission.

vim hello.sh

chmod +x hello.sh

Specify the absolute path: /hello.sh
Specify the relative path: ./hello.sh

Insert picture description here

Method 2: Specify Shell to interpret the script, and the file does not require x permission.
sh script path: sh hello.sh
source script path: hello.sh or source hello.sh

Insert picture description here

(5) Pipeline and redirection

1. Pipeline operation

The output result of the command on the left side of the pipe symbol "|" is used as the input (processing object) of the right command. Multiple pipes can be used in the same line of command.
ps aux | wc -l # Check how many processes there are
echo "abc123" | passwd --stdin zhangsan # Change password for user Zhang San

Insert picture description here

2. Redirect

Interactive hardware 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

Insert picture description here

echo "123456" > pass.txt
passwd --stdin zhangsan < pass.txt

Insert picture description here

ls -lh > log.txt 2>&1 等同于 ls -lh &> log.txt
本来1-->屏幕 (1指向屏幕)
执行>log后, 1-->log.txt (1指向log.txt)
执行2>&1后, 2-->1 (2指向1,而1指向log.txt,因此2也指向了log.txt)

Two, Shell script variables

(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 system environment

(2) Classification of variables

Custom variables: defined, modified and used by the user.
Environment variables: maintained by the system and used to set the working environment.
Location variables: pass parameters to the script program through the command line.
Predefined variables: a type of variable built in Bash that cannot be modified directly

1. Custom variables

Define a new variable. The
variable name starts with a letter or an underscore. It is case sensitive and all uppercase is recommended

格式:变量名=变量值

PRODUCT=python

VERSION=2.7.13

View the value of a variable
格式:echo $变量名

echo $PRODUCT

echo $VERSION

echo "$PRODUCT"

echo $PRODUCT$VERSION

Insert picture description here

赋值时使用引号
双引号:允许通过$符号引用其他变量值 (需要把$放入括号内)
单引号:禁止引用其他变量值,$视为普通字符
反撇号:命令替换,提取命令执行后的输出结果,`...`.和$()作用相同

Insert picture description here
Insert picture description here

The read command gets the input

method one:
read -p "提示信息" 变量名
echo $变量名

vim name.sh

Insert picture description here
Insert picture description here

Method Two:
echo -n "提示信息"
read 变量名
echo $变量名

Insert picture description here

Insert picture description here

(3) 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 the subroutine or new sub-Shell environment, local variables can no longer be used.
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.

格式1:export 变量名
格式2:export 变量名=变量值

Insert picture description here

可以使用 pgtree 命令查看Shell环境,
输入 bash 命令进入子Shell环境,
按Ctrl+D组合键或输入 exit 命令退出子Shell环境

(4) Operation of integer variables

格式:expr 变量1 运算符 变量2 [运算符 变量3]
运算符:+ 加法、- 减法、\* 乘法、/ 除法、% 取余

Insert picture description here

Commonly used operation expressions:
i=$(expr 12 \* 5)
i=$((12 * 5))
i=$[12 * 5]
let i=12*5

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

Insert picture description here
Insert picture description here

2. Environmental variables

Environment variables are created in advance by the system to set the user’s working environment

Configuration files: /etc/profile, ~/.bash_profile

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

Insert picture description here

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

Insert picture description here

The global configuration file for environment variables is /etc/profile, and the variables defined in this file apply to all users. Each user also has its own independent profile (~/.bash_profile). Can be used to change or set an environment variable for a long time.
vim /root/.bash_profile
export HISTSIZE=200 #修改root用户的历史命令记录条数

echo $HISTSIZE
source /root/.bash_profile #读取并执行文件中的设置
echo $HISTSIZE

3. The readonly command sets read-only variables

product=benet
readonly product #设置为只读变量
echo $product
product=accp #只读变量不可以被重新赋值
unset product #只读变量不可以被删除,unset 命令用于删除变量

Insert picture description here

4. Location 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.
$n: n is a number, $0 represents the command itself, $1- 9 represents one to the ninth parameter, parameters above ten need to be expressed in braces, for example, the tenth parameter is 9 represents one to the ninth parameter. Parameters above ten need to be expressed in braces, for example, the tenth parameter is9 Generation table with a th to the first nine th parameter numbers , ten to the the reference number required to make a large enclosed number table shows , than such first ten th parameter number is {10}

vim addnum.sh
num1=$1
num2=$2
sum=$(($num1 + $num2))
echo $sum

./addnum.sh 12 34
$0 $1 $2

Insert picture description here
Insert picture description here

5. Predefined variables

$@$*:表示命令或脚本要处理的参数。
$*:把所有参数看成以空格分隔的一个字符串整体,代表"$1 $2 $3 $4"$@:把各个参数加上双引号分隔成n份的参数列表,每个参数是独立的,代表"$1" "$2" "$3" "$4"$0:表示当前执行的脚本或命令的名称。
$#:表示命令或脚本要处理的参数的个数。	
$?:表示前一条命令或脚本执行后的返回状态码,返回值为0表示执行正确,返回任何非0值均表示执行出现异常。也常被用于Shell脚本中return退出函数并返回的退出值。

Write a script to see the difference:

vim bianliang.sh

Insert picture description here

Insert picture description here

vim mybak.sh
#!/bin/bash
time=backup-date +%F.tgz
tar zcf $time $* &> /dev/null #/dev/null表示的是一个黑洞文件,通常用于丢弃不需要的数据输出
echo "已执行 $0 脚本,"
echo "共完成 $# 个对象的备份"
echo "具体内容包括: $*"

chmod +x mybak.sh
./mybak.sh /etc/passwd /etc/shadow

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51573771/article/details/111242446