Linux shell programming specifications and variables and judgment statements

1. Shell brief introduction

1.1What is shell

Translator function, an application that communicates with the kernel. Translate the code into binary and let the kernel process it. It is responsible for receiving the operation instructions (commands) input by the user and interpreting them, passing the operations that need to be performed to the kernel for execution, and outputting the execution results.

1.2linux的shell:/etc/shells

When the user uses a command, the system will detect this file to obtain the content, and only relevant commands can be used within the command.
bash (/bin/bash) is the default shell used by most current Linux versions.
Insert image description here

2. shell script

2.1shell script file format: .sh

2.2 Run shell script command:

1.sh first.sh
2.bash first.sh
3.source first.sh
4../first.sh(需要赋予权限)

2.3 Run a simple shell script

vim test.sh  //创建一个sh类型的文件

Insert image description here

bash test.sh  //运行刚才创建的文件

Insert image description here

2.3 Script execution logic and execution method

脚本执行逻辑
1. 顺序执行:程序按从上到下顺序执行
2. 选择执行:程序执行过程中,根据条件的不同,进行选择不同分支继续执行
3. 循环执行:程序执行过程中需要重复执行多次某段语句

Execution method:
Specify the path to execute the file (requires execution permission)

   [root@localhost ~]# chmod +x /root/host.sh    加权限
   指定相对路径./host.sh
   指定绝对路径/root/host.sh

Specify the interpreter to execute (no permissions required)

#!/bin/bash 此处指定的shell为bash,则bash不需要权限也可以执行

source and . (no permissions required)

#执行方式三#
source 脚本名(绝对路径)
source /root/host.sh 
或者
. /host.sh 

2.4Shell script error debugging

  • Syntax errors
    will cause subsequent commands to not continue to execute. You can use bash -n to check for errors. The number of error lines prompted may not be accurate.

  • Command error
    By default, subsequent commands will continue to be executed and cannot be checked using bash -n. You can use bash -x to observe.

  • Logical errors
    can only be debugged using bash -x.

bash -x    #模拟执行,可以逐条排错
bash -n    #检查语法错误

2.5 Advantages of scripts

1.自动化运维
2.批量化重复操作可以编写脚本结合计划任务自动周期运行
3.减轻管理员工作量
4.提高处理文本文件的速度
5.避免配置出错

2.6 Operators

1.加法 +
2.减法 -
3.乘法 \ *
4.除法 /(只会显示整数,除不尽为0)
5.取余 (取模)% 
(1) let var=算术表达式
let sum=1+2
sum=1+2
(2) $((var=算术表达式)) 和上面等价
((sum=1+2))
echo $sum
(3) var= $[算术表达式]
(4) var=$((算术表达式))
(5) var=$(expr arg1 arg2 arg3 ...)
(6) var= expr arg1 arg2 arg3 ...
(7) echo '算术表达式' | bc

  $[ ]
  $(())
  $(expr 1 2 3)

#let
[root@localhost ~]#a=1
[root@localhost ~]#b=2
[root@localhost ~]#let z=a+b
[root@localhost ~]#echo $z
3
[root@localhost ~]#let z=$[a-b]
[root@localhost ~]#echo $z
-1
[root@localhost ~]#let z=$((a-b))
[root@localhost ~]#echo $z
-1

#expr
[root@localhost ~]#a=1
[root@localhost ~]#b=2
[root@localhost ~]#expr $a + $b
#加减乘除前后有空格
3

[root@localhost ~]#echo "6*3"|bc
18
echo  $[RANDOM%34 +1]

let 支持加加减减 使用较多
[root@localhost ~]#i=1
[root@localhost ~]#let i++
[root@localhost ~]#echo $i
2
[root@localhost ~]#i=1;let i++;echo $i
2
[root@localhost ~]#i=1;let ++i;echo $i
2
[root@localhost ~]#i=100;let j=i++;echo $i $j
101 100
[root@localhost ~]#i=100;let j=++i;echo $i $j
101 101
#i++ 是先赋值给j后再加     ++i是加后再赋值

i++  是先赋值再加
++i  是加后再赋值

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 ]

2.7 Algorithm

1.加法: num1 + num2
2.减法:num1 - num2
3.乘法:num1 \ * num2
4.整除:num1 / num2
5.取余(求模):num1 % num2 (求 num1 除以 num2 的余数)

Insert image description here

3. Redirection and pipe characters

3.1 Redirect

type 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
type Operator use
Redirect input < Read data from the specified file instead of entering it from the keyboard
Redirect output 1> Save the output results to the specified file (overwriting the original content)
>> Append the output results to the end of the specified file
standard error output 2> Save the error message to the specified file (overwriting the original content)
2>> Standard error output is appended to the end of the specified file
mixed output &>Redirect regardless of right or wrong Save the contents of standard output and standard error to the same file

Insert image description here
Insert image description here
Insert image description here

[root@localhost ~]#ls /data /error >all.log 2>&1
#既有错误也有正确 &符号表示分隔符
[root@localhost ~]#cat all.log 
ls: 无法访问/error: 没有那个文件或目录

[root@localhost ~]#ls /data /error >all.log 2>1
#如果没有&会生成一个 1文件 将错误导入

Insert image description here

3.2 Pipe character

|: Mainly used to process text. The output result of the command on the left side of the pipe symbol "|" is used as the input (processing object) of the command on the right side. Multiple pipes can be used in the same line of commands.

将user用户的密码改为123123

Insert image description here

4. Variables

4.1 Common variable types

自定义变量:由用户自己定义,修改和使用
环境变量:由系统维护,用于设置工作环境
只读变量:只可以读取不可以更改
位置变量:通过命令行给脚本传递参数
预定义变量:Bash中内置的一类变量,不能修改    有些规定好的变量 放在那里让你使用

4.2 Naming requirements

- 区分大小写
- 不能使程序中的保留字和内置变量:如:if, for,hostname   命令  a=
- 只能使用数字、字母及下划线,且不能以数字开头,注意:不支持短横线 “ - ”,和主机名相反
- 不要使用内置的变量,使用英文尽量使用词义通俗易懂,PATH              
- 大驼峰 StudentFirstName 
- 小驼峰 studentFirstName 
- 下划线 student_name
弱引用和强引用
"$name " 弱引用,其中的变量引用会被替换为变量值
'$name ' 强引用,其中的变量引用不会被替换为变量值,而保持原字符串

Insert image description here
Insert image description here

4.3 read -p

Insert image description here
Insert image description here

4.4 Convert local variables to global variables

Local variables: Newly defined variables are only valid in the current shell environment. When entering a subroutine or a new shell environment, local variables will no longer work.
Global variables: can continue to be used in new shell environments.
Convert local variables to global variables through the internal command export

格式1:export  变量名
格式2:export  变量名=变量值
#可以使用pstree 查看shell的环境
#输入bash进入子shell
#ctrl+D组合exit 退出子shell
[root@localhost opt]# abc=123
[root@localhost opt]# echo $abc 
123
[root@localhost opt]# bash
[root@localhost opt]# echo $abc
为空
[root@localhost opt]# exit
exit
[root@localhost opt]# echo $abc
123
[root@localhost opt]# export abc
#export  变量名      定义全局变量
[root@localhost opt]# bash
[root@localhost opt]# echo $abc
123

4.5 Environment variables

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

env   #可以看到当前所有的环境变量

4.5.1 Commonly used environment variables

  • $USER represents the user name
    Insert image description here
  • $HOME represents the user's home directory
    Insert image description here
  • $LANG represents language and character set
    Insert image description here
  • $PWD represents the current working directory
    Insert image description here
  • $PATH represents the default path for executable user programs
    Insert image description here

4.5.2 Global configuration file of environment variables

#配置文件位置
/etc/profile 
##修改此文件,全局生效,可用于长期变更或设置环境变量

4.6 Read-only variables

  • After a variable is declared read-only, its value cannot be modified.
readonly 变量名 #将变量声明为只读变量

4.7 Position variables

$1, $2, $3, … $n represents the positional value of the command line parameter.
$1 represents the first parameter, $2 represents the second parameter, and so on.
When n is greater than 9, { } needs to be added. For example, the tenth position must be represented by ${10}.

#以shell脚本为例
#!/bin/bash
echo "$1"            #位置1
echo "$2"            #位置2
echo "$3"            #位置3
echo "${10}"         #位置10
echo "$10"           #位置1和0

Insert image description here

4.8 Predefined variables

The system has defined it for you and you can use it.

  • $*: Indicates that the contents of all positional parameters are returned as a whole and all are returned.
  • $@: Indicates that the content of all positional parameters is divided into n parts, and each part is returned as an independent individual. Returns all
  • $?: Indicates the return status after the execution of the previous command. A return value of 0 indicates that the execution is correct. Returning any non-0 value indicates that an exception occurred during the execution.
  • $#: represents the total number of positional parameters in the command line
  • $0: Indicates the name of the currently executed script or program. The name of the current script.
  • $$: current process id
  • $!: The last id of the background task

5. Conditional statements

5.1 Testing

test 测试文件的表达式 是否成立
格式1:test  条件表达式
格式2:[  条件表达式  ]
注意[]空格,否则会失败
测试 是否成功使用 $?  返回值
[ 操作符 文件或目录 ]
help test
操作符:
-d:测试是否为目录(Directory)
-e:测试目录或文件是否存在(Exist)
-a:测试目录或文件是否存在(Exist)
-f:测试是否为文件(File)
-r:测试当前用户是否有权限读取(Read)
-w:测试当前用户是否有权限写入(Write-x:测试当前用户是否有权限执行(eXcute)
-L: 测试是否为软连接文件

属性测试补充:
-s FILE #是否存在且非空
-t fd #fd 文件描述符是否在某终端已经打开
-N FILE #文件自从上一次被读取之后是否被修改过
-O FILE #当前有效用户是否为文件属主
-G FILE #当前有效用户是否为文件属组

If true, the status code variable $? returns 0.
If false, the status code variable $? returns 1.

Insert image description here
Insert image description here

[root@localhost ~]# test -e qiuhe.sh &&echo "yes"
yes
&&表示且的意思 前面的表达式成立才会输出yes

5.2 Comparing integer values

[Integer 1 Operator Integer 2] Formula

  • -eq: The first number is equal to (Equal) the second number
  • -ne: the first number is not equal to (Not Equal) the second number
  • -gt: the first number is greater than (Greater Than) the second number
  • -lt: the first number is less than (Lesser Than) the second number
  • -le: the first number is less than or equal to (Lesser or Equal) the second number
  • -ge: the first number is greater than or equal to (Greater or Equal) the second number
[  整数1  操作符  整数2  ]
[root@test1 ~]# a=2        实例
[root@test1 ~]# b=3
[root@test1 ~] [ $a -eq $b ]
[root@test1 ~]# echo $?
1
[root@test1 ~]# [ 2 -le 3 ]
[root@test1 ~]# echo $?
0

Insert image description here

5.3 String comparison

Commonly used test operators

  • =: The string contents are the same
  • !=: The content of the string is different, and the sign ! indicates the opposite meaning
  • -z: The string content is empty
  • -n: Whether the character exists

Format
[String 1 = String 2] Is it the same
[String 1 != String 2] Is it different
[-z string] Is it empty
[-n string] Does the character exist
[root@localhost data]# str1=wang
[root@localhost data]#str2=zhou
[root@localhost data]#[ $str1 = $str2 ]
[root@localhost data]#echo $?
1

[root@localhost etc]# [ $USER = root ]&& echo true
true
[root@localhost etc]# [ $USER != root ]&& echo true

[root@localhost etc]# read -p "yes/no:" ack
yes/no:
[root@localhost etc]# echo $ack 

[root@localhost etc]# [ -z $ack ] && echo true 
true
[root@192 ~]# read -p "是否覆盖当前文件 (yes/no)" ACK
是否覆盖当前文件 (yes/no)yes
[root@192 ~]# [ $ACK = "yes" ] && echo "覆盖"
覆盖
[root@192 ~]# read -p "是否覆盖当前文件 (yes/no)" ACK
是否覆盖当前文件 (yes/no)no
[root@192 ~]# [ $ACK = "no" ] && echo "不覆盖"
不覆盖

5.4 Logic test (short circuit operation)

Format 1: [expression 1] operator [expression 2]…
Format 2: command 1 operator command 2…

common conditions

  • -a or &&: logical AND, "and" is true only when all the meanings of "and" are true
  • -o or ||: logical or, "or" means that it is true if it is true
  • !: logical no
  • [root@192 ~]# [ ! -d mmm ] && echo “yes”
    yes
[root@localhost etc]# [ 4 -lt 5 ]&&echo true || echo false
true
[root@localhost etc]# [ 4 -gt 5 ]&&echo true || echo false
false
[root@localhost etc]# [ 4 -gt 5 ]&& echo true ||echo false
false

|| 只有前面不成立时才会执行后面的操作

合并条件
[root@localhost etc]# [ $a -ne 1 ]&&[ $a != 2 ]
[root@localhost etc]# echo $?
0
[root@localhost etc]# [ $a -ne 1 -a  $a != 2 ]
[root@localhost etc]# echo $?
0
[root@localhost etc]# [[ $a -ne 1 &&  $a != 2 ]]
[root@localhost etc]# echo $?
0

Insert image description here
Insert image description here
Insert image description here
Insert image description here

5.5 Structure of if statement

5.5.1if statement

Single branch if statement:
       if
       then
       fi

Double branch if statement:
      if [ ]
      then
      else
      if

Multi-branch if statement:
      if [ ]
      then
      elif [ ]
      then
      fi

5.5.2case

Statement format: case variable in
        mode 1)
          command
          ;;
          mode 2)
          command
          ;;
          *)
          command
          ;;
          esac

case支持glob风格的通配符:
* 任意长度任意字符
? 任意单个字符
[0-9] 指定范围内的任意单个字符
|   或者,如: a|b

Insert image description here

5.2.3echo

echo -n   表示不换行输出
echo -e   表示输出转义符
常用的转义符
Options effect
\r The cursor moves to the beginning of the line without wrapping
\s The name of the current shell, such as bash
\t Insert Tab key, tab character
\n output newline
\f Wraps a new line, but the cursor remains where it was
\ Indicates inserting "\" itself to escape
\b Indicates that backspace does not display the previous character
\c Suppress more output or not wrap
[root@localhost ky15]#echo -e "12345\b678"
##退格删除前面的字符
1234678
[root@localhost ky15]#echo -e "12345\b\b678"
123678
[root@localhost ky15]#echo -e "12345\b\b\b678"
12678
[root@localhost ky15]#echo -e "12345\b\b\b\b678"
16785
###注意退格键和末尾的字符相关,超过末尾的字符数量 会出bug 了解即可

[root@localhost ky15]#echo -e "12345678\c"
12345678[root@localhost ky15]#echo -e "1234\c5678"
1234[root@localhost ky15]#
###\c 注意 使用在数字中间会把后面内容删除

5.2.4date

date to view the current system time

  • -d The date you describe displays the time described by the specified string instead of the current time
  • %F complete date format, equivalent to %Y-%m-%d
  • % T time (24-hour format) (hh:mm:ss)
[root@localhost ~]# date -d '-1 day' +%F 
2021-10-21

[root@localhost ~]# date  +%F 
2021-08-19
[root@localhost ~]# date -d '1 day ' +%F-%T
2021-08-20-23:28:42
[root@localhost mnt]# date -d "-3 day"      前三天
2021年 08月 18日 星期三 11:30:15 CST
[root@localhost mnt]# date -d "+3 day"  后三天
2021年 08月 18日 星期三 11:30:15 CST
[root@localhost data]#date -d '1 day ' +%F'     '%T
2021-10-22     00:45:37

6. Real-world use cases

Check whether the test.sh file in the user's home directory exists and whether it has execution permissions
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/m0_62231324/article/details/132259490