What is 21.2 shell?
The shell is a command-line interpreter that provides the user with an interface system-level program that sends a request to the Linux kernel to run the program, allowing the user to start, suspend, stop, or even write programs with the shell.
21.3 Shell Programming QuickStart 21.3.1 script format requirements
(1) script starts with #!/bin/bash
(2) script requires executable permissions
21.3.2 writing the first shell script
Create a shell script that outputs Hello world!
Common ways to execute 21.3.3 scripts
Mode one (enter the absolute path or relative path of the script)
(1) First to give myshell.sh script x permission
(2) Execute script
Way two (sh+ script), not recommended
Description: Do not give script x permission to execute directly
21.4 Shell variables 21.4.1 Shell variable Introduction
(1) The variables in the Linux shell are divided into, system variables and user-defined variables.
(2) System variables: $HOME, $PWD, $SHELL, $USER, and so on.
(3) Displays all variables in the current shell: set
21.4.2 the definition of shell variables
Basic syntax
(1) Defining variables: variable = value
(2) Undo variable: unset variable
Quick Start
(1) Define variable a
(2) Undo variable A
(3) Declare static variable b=2, cannot unset
21.4.3 rules for defining variables
(1) Variable names can consist of letters, numbers, and underscores, but cannot begin with a number.
(2) There must be no spaces on either side of the equals sign.
(3) Variable names are generally used in uppercase.
21.4.4 assigning the return value of a command to a variable (emphasis)
(1) c = ' ls-l/home ' anti-quote, run the command inside and return the result to the variable C
(2) d=$ (date) is equivalent to the inverse quotation mark
21.5 Setting environment Variables 21.5.1 Basic syntax
(1) export variable name = variable value (output shell variable as environment variable)
(2) Source configuration file (make the modified configuration information effective immediately)
(3) Echo $ variable name (query the value of environment variable)
21.5.2 Quick Start
(1) Defining Tomcat_home environment variables in the/etc/profile file
(2) View the value of the environment variable Tomcat_home
Note: Before outputting the tomcat_home environment variable, you need to make it effective
(3) using Tomcat_home in another shell program
21.6 position parameter Variable 21.6.1 introduction
When we execute a shell script, if we want to get the parameter information to the command line, we can use the positional parameter variable, for example:./myshell.sh 100 200, this is a command line to execute the shell, you can get the parameter information in the Myshell script.
21.6.2 Basic Syntax
$n (n is a number, and $ A represents the command itself, $1-$9 represents the first to the Nineth argument, and more than 10 of the arguments need to be enclosed in curly braces, such as ${10})
$* (this variable represents all parameters in the command line, $* all parameters as a whole)
[Email protected] (this variable also represents all parameters in the command line, but [email protected] treats each parameter differently)
$# (this variable represents the number of all parameters in the command line)
21.6.3 position parameter Variable application example
Write a shell script positionpara.sh to get the various parameter information of the command line in the script
21.7 pre-defined variables
is a variable that the shell designer has defined beforehand and can be used directly in the shell script.
$$ (Process number (PID) of the current process)
$! (The process number (PID) of the last process running in the background)
$? (The return status of the last command executed.) If the value of this variable is 0, it proves that the previous command was executed correctly, and if the value of this variable is not 0 (which is the parameter, which is determined by the command itself), it proves that the last command was executed incorrectly. )
21.8 operator
(1) "$ ((OP))" or "$[-op"
(2) Expr m + N Note that there is a space between the expr operators (+,-,*,/,%)
21.9 article judgment
[Condition] (note that there are spaces before and after condition)
#非空返回true, you can use $? authentication (0 is true,>1 to false)
(1) A comparison of two integers
= string comparison
-lt less than
-le less than or equal to
-eq equals
-GT Greater than
-ge greater than or equal to
-ne Not equal to
(2) According to the file permissions to judge
-R has Read permission "-R file"
-W has Write permission
-X has permission to execute
(3) Judging by file type
-F file exists and is a regular file
-E File exists
-D file exists and is a directory
21.10 Process Control 21.10.1 if judgment
If [conditional judgment]
Then
Program
elif [Conditional Judging type]
Then
Program
Fi
NOTE: [Conditional judgment], there must be a space between the brackets and the conditional judgment
21.10.2 Case Statement
Case $ variable name in
"Value 1")
If the value of the variable equals the value 1, execute the program 1
;;
"Value 2")
If the value of the variable equals the value 2, execute the program 2
;; *)
If the value of the variable is not the above value, the program is executed
;;
Esac
21.10.3 for Loop
Basic Syntax 1:
For variable in value 1 value 2 value 3 ...
Do
Program
Done
Basic Syntax 2:
for (initial value; cyclic control condition; variable change)
Do
Program
Done
21.10.4 while loop
While [conditional-judging]
Do
Program
Done
21.11 Read console input
Read (options) (parameters)
Options:
-P: Specifies the prompt to read the value;
-T: Specifies the time to wait (in seconds) to read the value, and no longer waits if it is not entered within the specified time.
Parameters
Variable: Specifies the variable name of the Read value
21.12 functions
Shell programming, like other programming languages, has system functions and can also customize functions.
System functions
BaseName (returns the last part of the full path, often used to get the file name)
basename [pathname] [suffix]
basename [string] [suffix]
Suffix is a suffix, and if suffix is specified, basename will remove suffix from pathname or string.
DirName (returns the previous part of the full path, often used to return the LU path portion)
DirName file Absolute Path (removes the file name (part of the non-directory) from the given file name containing the absolute path, and then returns the remaining path (part of the directory))
Custom functions
[function] funname[()]
{
Action;
[Return int;]
}
Call Direct Write function name: funname [value]
21.13 Shell Programming Comprehensive case
Requirements Analysis:
(1) Daily 2:10 Backup database DB1 to/data/backup/db
(2) The backup start and the end of the backup can give the corresponding prompt information
(3) The backup file requires the backup time as the file name and is packaged as a. tar.gz form, such as 2018-05-04_154833.tar.gz
(4) At the same time as the backup, check whether there are 10 days ago Backup database files, if any, delete them.
The script code is as follows (mysql_db_backup.sh):
#!/bin/bash
#完成数据库的定时备份.
#备份的路径
backup=/data/backup/db
#当前的时间作为文件名
datetime=$ (Date +%y_%m_%d_%h%m%s)
#可以输出变量调试
#echo ${datetime}
echo "======= Start Backup ========"
echo "The path to the ======= backup is $BACKUP/$DATETIME. tar.gz"
#主机
Host=localhost
#用户名
Db_user=root
#密码
db_pwd=123456
#备份数据库名
Database=db1
#创建备份的路径
#如果备份的路径文件夹存在, use it, or create
[!-D "$BACKUP/$DATETIME"] && mkdir-p "$BACKUP/$DATETIME"
#执行mysql的备份数据库的指令
Mysqldump-u${db_user}-p${db_pwd}--host= $HOST $DATABASE | gzip > $BACKUP/$DATETIME/$DATETIME. sql.gz
#打包备份文件
CD $BACKUP
TAR-ZCVF $DATETIME. tar.gz $DATETIME
#删除临时目录
RM-RF $BACKUP/$DATETIME
#删除10天前的备份文件
Find $BACKUP-mtime +10-name "*.tar.gz"-exec rm-rf {} \;
echo "===== backup file successfully ==========="
Attention:
Sometimes when the MySQL program is installed, the direct Input command mysql or mysqldump will find that the prompt command does not exist, this is because the system will default to find the command under/usr/bin, if this command is not in this directory, of course, will not find the command
solutions;
First you need to know the full path to the MySQL command or mysqldump command, and you can use the Find command to find
Find/-name Mysql-print
For example, the path to MySQL is:/usr/local/mysql/bin/mysql, and then map a link to the/usr/bin directory, the equivalent of creating a linked file
Ln-s/usr/local/mysql/bin/mysql/usr/bin
Shell Foundation Programming