Introduction to shell scripting
- The shell is a scripting language aming_linux blog.lishiming.net
- You can use syntax such as logical judgment, loop, etc.
- customizable function
- A shell is a collection of system commands
- Shell script can realize automatic operation and maintenance, which can greatly increase our operation and maintenance efficiency
Public number: aming_linux
Blog: blog.lishiming.net
Shell script structure and execution
The beginning (first line) needs to be added: #!/bin/bash
here means that the file uses bash syntax and is executed through the /bin/bash interpreter.
Lines beginning with # are used as explanations:
The name of the script ends with .sh to distinguish it as a shell script
There are two ways to execute the .sh script:
1 First add x permissions to the .sh script:
chmod +x 1.sh
Absolute path to .sh script Enter:
/root/1.sh
2bash (bash=sh) executes the .sh script:
bash 1.sh
View the script execution process:
sh -x 1.sh
Detect syntax errors in shell scripts:
sh -n 1.sh
date command usage
Most of the date command in a shell script is to change the filename of the log, and to distinguish the date of some files.
View current time
[root@shuai-01 ~]# date
2018年 02月 25日 星期日 14:51:35 CST
[root@shuai-01 ~]# LANG=en
[root@shuai-01 ~]# date
Sun Feb 25 14:52:25 CST 2018
date +%Y : print the four-digit year
[root@shuai-01 ~]# date +%Y
2018date +%y : print the year with two digits
[root@shuai-01 ~]# date +%y
18date +%m : print month
[root@shuai-01 ~]# date +%m
02date +%d : indicates the date
[root@shuai-01 ~]# date +%d
25date +%H : indicates the hour
[root@shuai-01 ~]# date +%H
14date +%M : indicates minutes
[root@shuai-01 ~]# date +%M
58date +%S : indicates seconds
[root@shuai-01 ~]# date +%S
35date +%w : means week, 0 means Sunday
[root@shuai-01 ~]# date +%w
0Indicates the year, month and day:
[root@shuai-01 ~]# date +%Y%m%d
20180225[root@shuai-01 ~]# date +%F
2018-02-25
Indicate time:
[root@shuai-01 ~]# date +%T
18:44:10
Show calendar:
[root@shuai-01 ~]# cal
February 2018
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
date marks yesterday's date:
[root@shuai-01 ~]# date -d "-1 day"
Sat Feb 24 18:47:16 CST 2018
[root@shuai-01 ~]# date -d "-1 day" +%F
2018-02-24
Variables in Shell Scripts
1. 当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替
2. 使用条件语句时,常使用变量 if [ $a -gt 1 ]; then ... ; fi
3. 引用某个命令的结果时,用变量替代 n=`wc -l 1.txt`
4. 写和用户交互的脚本时,变量也是必不可少的 read -p "Input a number: " n; echo $n 如果没写这个n,可以直接使用$REPLY
5. 内置变量 $0, $1, $2… $0表示脚本本身,$1 第一个参数,$2 第二个 .... $#表示参数个数
6. 数学运算a=1;b=2; c=$(($a+$b))或者$[$a+$b]