Shell Programming I. Introduction to the Program
Program
程序:算法+数据结构数据结构:数据在计算机中的类型和组织方式算法:处理数据的方式面向过程:以指令为中心,数据服务于指令面向对象:以数据为中心,指令服务于数据计算机:二进制执行
Advanced Programming Languages:
编译:高级语言->编译器->机器代码->执行解释:高级语言->执行->解释器->机器代码 shell
Three major logic
顺序、循环、选择
Two. shell script 1. Format
格式要求:首行shebang机制#!/bin/bash 指定shell类型# 注释程序名,作用说明,版本信息,作者信息bash -n 检查语法错误bash -x 跟踪调试脚本的执行过程
2. Variables
Types of variables:
字符、整型强类型弱类型不需要声明变量类型不支持浮点型都以字符串的形式存储
Naming rules:
不能是内部命令、系统关键字字母、数字、下划线不能以数字开头
Defining variables
a=linuxa=‘linux‘a="linux"上面三个都是把linux这个字符串赋值给变量a,如果赋值的一方当中没有空格,则不用引号,如果有空格则必须用引号。
Using variables
echo $aecho ${a}调用变量a,在变量前面加上$即可,变量用{}括起来是个良好的习惯已经定义的变量也可以重新赋值a=centosunset a 删除变量readonly a 只读变量,不能修改
The difference between single and double quotes
单引号 ‘‘ 强引用,单引号里所有内容都作为字符输出双引号 "" 若引用,双引号里有变量的时候,会读取变量值输出,而不是直接输出
Assigning command execution results to variables
a=`cat /etc/fstab` 使用反向单引号a=$(cat /etc/fstab) 使用$()反向单引号容易和单引号混淆,因此推荐使用$()
Local variables and global variables
局部变量:生效范围是当前shell进程 全局变量:生效范围是当前shell及其子进程export a 声明全局变量set 显示变量,自定义和系统自带的export 或 declare 显示环境变量echo $PPID 显示父进程编号pstree -p 显示进程信息source 运行的脚本在本bash环境下,会修改某些当前bash下的环境。bash 运行脚本时会新开一个bash,为当前bash的子进程,不会影响当前环境SHLVL 变量,shell 的嵌套深度echo $_ 上一个命令的最后一个字符串unset name 删除变量,除了只读变量readonly 查看只读变量 declare -r (umask=0022;touch a) () 不开启子进程{} 开启子进程
Positional variables
$$ 当前shell的ID$1 第一个参数$* 所有参数,认为所有参数是一个整体[email protected] 所有参数,认为所有参数是独立的个体$# 参数数量$0 当前脚本的文件名10以上的加{}shift n 变量按顺序往前移动n个变量set -- 清除变量
Exit status
2. Operations
Bash supports arithmetic operations, relational operations, Boolean operations, String operations, and file test operations
Arithmetic operations
expr 2 + 4echo `expr 2 + 4a=`expr 2 + 4`c=`expr $a + $b`expr是一款表达式计算工具,数值和运算符之间必须有空格,调用整个表达式的时候记得加``let sum=x+y$[x+y]$((x+y))expr 2 + 3 expr是一个命令declare -i n=10
operator |
Description |
Example |
+ |
Addition |
' Expr $a + $b |
- |
Subtraction |
' Expr $a-$b |
* |
Multiplication |
' Expr $a \* $b |
/ |
Division |
' Expr $a/$b |
% |
Take surplus |
' Expr $a% $b |
= |
Assign value |
A= $b |
== |
Compare two numbers for equality |
[$a = = $b] |
!= |
Compare two numbers for different sizes |
[$a! = $b] |
Spaces are required between expressions and []
Logical operations
true 1 ;false 0;与 & 有0即0或 | 有1即1非 ! 取反短路与 && 前一个为假则不再判断第二个短路或 || 前一个为真则不再判断第二个异或 ^ 相同为假,相异为真同或 相同为真,相异为假
Test command:
test 不支持正则表达式,没值就为假,变量加“” [[]] 支持正则表达式[] 有值就为真[] 和变量之间要加空格
The use of several parentheses
(; ; ) 几个命令一起执行,开启子shell{; ; } 几个命令一起执行,不开启子shell,前后空格,最后一个加;号[] 逻辑判断,不支持正则表达式[[]] 逻辑判断,支持正则表达式,一般用[]=~ 匹配,字符串不要加"",支持正则表达式 != 不等== 相等,字符串不要加"",支持通配符
Relationship operator
数值测试,不支持字符
operator |
Description | Full
name |
-gt |
is greater than |
Greater than |
-ge |
is greater than or equal to |
Greater than equal |
-eq |
is equal to |
Equal |
-ne |
is not equal to |
No equal |
-lt |
is less than |
Less than |
-le |
is less than or equal to |
Less equal |
String test
= 是否等于> ascii码是否大于< 是否小于!= 是否不等于=~ 左侧字符串是否能够被右侧的pattern匹配,一般用于[[]]中-z "string" 字符串是否为空,空为真,非空为假-n "string" 字符串是否不空,不空为真,空位假
File test
-a / -e file :文件存在性测试,存在未真,否则为假-b 是否存在且为块设备文件-c 是否存在且为字符设备文件-d 是否存在且为目录文件-f 是否存在且为普通文件-h / -L :存在且为链接文件-p 是否存在且为命名管道文件-S 是否存在且为套接字文件
Permission test
-r 是否存在且可读-w 是否存在且可写-x 是否存在且可执行-u 是否存在且拥有suid权限-g 是否存在且拥有sgid权限-k 是否存在且拥有sticky权限
File properties
-s 是否存在且为非空-t 文件描述符是否在某终端打开-N 文件自从上一次被读取之后是否被修改-O 当前有效用户是否为文件时属主-G 当前用户是否为文件属组
Binocular test
file1 -ef file2:1是否是2的硬链接file1 -nt file2:1是否新于file2file1 -ot file2:1是否旧于file2-a 并且-o 或者! 非
3. String
Single quotation marks
str=‘this is a string‘ 单引号里的任何字符都会原样输出,单引号里的变量是无效的单引号字符串中不能出现单引号,对单引号转义后也不行
Double quotes
str="you name is $name"双引号里可以有变量双引号里可以出现转义字符
Stitching strings
firstname="zhang"lastname="hw"echo $firstname $lastname 输出:zhanghw
Get string length
str="abcd"echo ${#str}
Extract substring
str="daxiong is the best girl"echo ${str:1:4} 1:4 起始字符到终止字符,由0开始
Finding substrings
str="daxiong is the best girl"echo `expr index "$str" is`
4. Arrays
Only one-dimensional arrays are supported and the array size is not qualified. Array elements The following table, starting with 0, can be an integer or an arithmetic expression with a value greater than or equal to 0
Defined
用括号来定义数组,各个元素间用空格分开,如下:array_name=(value0 value1 value2)单独定义array_name[0]=value0array_name[1]=value1
Reference
${array_name[index]}a=${array_name[0]}${array_name[@}} ${array_name[*]} @或* 可以获取数组中的所有元素
Gets the length of the array
a=${#array_name[@]} 取得数组元素的个数 @或*都可以a=${#array_name[n]} 取得下标为n的元素的长度
5.shell printf
The printf command is used for formatted output, and printf is defined by the POSIX standard, with better portability than echo
printf "hello\n" 输出字符串,printf不自带换行,需要在字符串最后添加\nprintf format-string [arguments]format-string为双引号$ printf "%d %s\n" 1 "abc"1 ab格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用$ printf %s abc defabcdef$ printf "%s\n" abc defabcdef$ printf "%s %s %s\n" a b c d e f g h i ja b cd e fg h ij如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替$ printf "%s and %d \n" and 0
6.if Else statement
- if...fi
- if...else...fi
- if...elif...else...fi
Must be closed at the end of FI.
Use of the IF statement
if [ expression ]then Statement(s) to be executed if expression is truefi如果expression返回ture,then后面的语句将会被执行;如果返回false则跳出循环
If.. Usage of else...fi statements
if [ expression ]then Statement(s) to be executed if expression is trueelse Statement(s) to be executed if expression is not truefi如果expression返回true则执行then后面的语句,否则执行else后面的语句
Usage of if...elif...fi statements
if [ expression 1 ]then Statement(s) to be executed if expression 1 is trueelif [ expression 2 ]then Statement(s) to be executed if expression 2 is trueelse Statement(s) to be executed if no expression is truefi哪一个expression 的值为true,就执行那个expression后面的语句,如果都为false则执行else后面的语句
7.for Cycle
for varibale in 列表do command1 command2 ...
8.while Cycle
The while loop is used to continuously execute a series of commands and to read data from the input file; the command is usually a test condition
While command
Do
Statement (s) to BES executed if command is true
Done
: Means true.
9.until Cycle
Until the loop is executed, the loop jumps out when the execution result is true.
Until command
Do
Statement (s) to being executed until command is true
Done
10.continue
跳过本次循环> break [N] 直接结束第N层的本轮循环,而直接进入下一轮判断,最内层为第1层,默认值为1 while command1 do if command2 then continue fi done
11.break
跳出整个循环break [N] 提前结束第N层循环,最内层为第一层while command1do if command2 then break fidone
12.shift
Shift [N]
Shifts the list of parameters to the left by the specified number of times, by default to the left. Once the list is moved, the left-most parameter is removed from the list.
#!/bin/bash#step through all the positional parametersuntil [ -z "$1" ] do echo "$1" shiftdoneecho
13.select
select variable in list do 循环体命令 done
The Select loop is used primarily to create menus, and menu items that are sorted numerically are displayed in the
Standard error, and displays the PS3 prompt, waiting for user input
The user enters a number in the menu list and executes the corresponding command
User input is saved in the built-in variable REPLY
Select is an infinite loop, so remember to exit the loop with the break command, or use the
The exit command terminates the script. You can also press CTRL + C to exit the loop
Select is often used in conjunction with case
Similar to a For loop, you can omit the in list and use positional parameters at this time
14.while Special Usage
while read linedo 循环体done < /path/from/somefile
Read each line in the/path/from/somelife file sequentially and assign the row to the variable line
15.case...esac
- Case...esca is a multi-branch selection structure
The case statement matches a value or a pattern, and if the match succeeds, the matching command is executed.
Case VALUE in
MODE1)
Command 1
Command 2
Command 3
;;
MODE2)
Command1
Command2
Command3
;;
Esac
The value must be followed by the keyword in, and each pattern must end with a closing parenthesis. The value can be either a variable or a constant.
;; Similar to break in other languages, it means jumping to the end of the entire case statement.
Shell Programming Basics