Shell Script Basics
脚本: 一个可以执行的文件,实现某种功能 – 需要提前设计、智能化难度大 – 批量执行、效率高 – 方便在后台静悄悄地运行
Standardize the general composition of shell scripts
? #! Environmental Declaration (what procedure to translate the following command)
? # comment Text
? Executable code
- Write a greeting/root/hello.sh script
– shows a phrase "Hello world!!"
[Email protected] ~]# vim/root/hello.sh
#!/bin/bash
echo Hello World
Hostname
Cat/etc/redhat-release
Uname-r
Ifconfig | Head-2
[Email protected] ~]# chmod +x/root/hello.sh
[Email protected] ~]#/root/hello.sh #绝对路径运行
####################################################
Grep-v ' ^# '/etc/login.defs | Grep-v ' ^$ '
REDIRECT Output
> : 只收集前面命令的正确输出 2> : 只收集前面命令的错误输出 &> : 收集前面命令的正确输出和错误输出
[Email protected] ~]# echo 123 >/opt/1.txt
[Email protected] ~]# cat/opt/1.txt/etc/
[Email protected] ~]# cat/opt/1.txt/etc/>/mnt/a.txt
[Email protected] ~]# Cat/mnt/a.txt
[Email protected] ~]# cat/opt/1.txt/etc/2>/mnt/a.txt
[Email protected] ~]# Cat/mnt/a.txt
[Email protected] ~]# cat/opt/1.txt/etc/&>/mnt/a.txt
[Email protected] ~]# Cat/mnt/a.txt
########################################################
Write a script that creates a user and sets a password of 123456
For the script to adapt to the changing environment, easy to use, so we have to use variables
Variable: Status quo, storing changeable value container with invariant name
In order to reduce the difficulty of using the script, we can generate interaction, in the form of questions and answers
READ: Input to the keyboard, assigned to the variable
-P: Screen output information
/dev/null:linux in black hole devices, designed to collect no output information
[Email protected] ~]# vim/root/user.sh
#!/bin/bash
Read-p ' Please enter the user name you want to create: ' ABC
Read-p ' Please enter the password you want to set: ' Pass
Useradd $abc &>/dev/null
echo $ABC User Creation success
echo $pass | passwd--stdin $abc &>/dev/null
echo $abc Password succeeded
[Email protected] ~]# chmod +x/root/user.sh
[Email protected] ~]#/root/user.sh
#########################################################
Use of variables
– Variable name = variable Value
– Easy to reuse a value with a fixed name
– Improved adaptability to mission requirements and operational environment changes
? Considerations when setting a variable
– If the specified variable name already exists, it is equivalent to re-assigning a value to this variable
– Don't have spaces on both sides of the equals sign
– Variable names can only be made up of letters/numbers/underscores, case-sensitive
– Variable names cannot start with a number, do not use keywords and special characters
######################################################
? Basic format
– Reference variable Value: $ variable Name
– View variable values: Echo $ variable name, echo ${variable name}
[Email protected] ~]# echo $a
[Email protected] ~]# echo rhel$a
[Email protected] ~]# Echo $a 00
[Email protected] ~]# echo ${a}00
######################################################
environment variable names are generally capitalized to set the user/system environment
Positional variables bash built-in to store command-line arguments provided when executing scripts
Predefined variables bash built-in, can be directly called special values, cannot be directly modified
Custom variables User self-set, modify and use
Environment variables User: Always store the current logged in user name
Positional variables: Non-interactive provides parameters for scripting
The position behind the script when executing the script, with the arguments 1 2 3 4 5, respectively. to store
[Email protected] ~]# vim/root/1.sh
#!/bin/bash
echo $
Echo
echo $
Echo $4
Echo ${10}
Echo ${11}
[[email protected] ~]#/root/1.sh haha xixi hehe lele hengheng DC TC DZ TZ 100 200 300
[Email protected] ~]# vim/root/2.sh
#!/bin/bash
Cat-n $
[Email protected] ~]#/root/2.sh/etc/redhat-release
Single quotes: Canceling the meaning of special characters
$ () and anti-apostrophe
: The output of the command as a parameter
[Email protected] opt]# rm-rf/opt/*
[Email protected] opt]# cd/opt
[[Email protected] opt]# Date
[Email protected] opt]# date +%f
[Email protected] opt]# mkdir mysql-$ (date +%f)
[[email protected] opt]# ls
[Email protected] opt]# mkdir hostname
-$ (date +%f)
[[email protected] opt]# ls
########################################################
Pre-defined variables
? The execution information used to save the script
– Use these variables directly
– You cannot assign values directly to these variables
$? Status value after program exit, 0 indicates normal, other value is abnormal
$# the number of position variables that have been loaded
$* values for all positional variables
[Email protected] opt]# vim/root/4.sh
#!/bin/bash
echo $
Echo
echo $
Echo ${10}
Echo $#
Echo $*
[[email protected] opt]#/root/4.sh 1 2 3 4 5 6 7 8 9 10
########################################################
Condition test
? Check file status
-E: Exists as true
-D: Exists and must be a directory to be true
-F: Exists and must be a file to be true
-r: Exists and must have Read permission to be true
-W: exists and must have write permission to be true
-X: Exists and must have execute permission to be true
? Compare integer size (with the E-letter ' equals ' two words)
-GT: Greater Than
-ge: greater than or equal to
-eq: Equals
-ne: Not equal to
-LT: Less than
-le: Less than or equal to
? string alignment
= =: equal to True
! =: Not equal to True
###################################################
If dual branch processing
If [conditional test];then
Execute command XX
Else
Execute Command yy
Fi
Determines whether a user exists, outputs the user's basic information if it exists, and creates the user if it does not exist
[Email protected] ~]# vim/root/4.sh
#!/bin/bash
Read-p ' Please enter the username you want to determine: ' User #将用户输入赋值给user
ID $user &>/dev/null #查看用户基本信息
If [$?-eq 0];then #判断上面命令是否成功 to determine if the user exists
echo $user user already exists
ID $user
Else
Useradd $user
echo $user User has created
Fi
Please use the Read command to read the IP address entered by the user
Determine if the computer can ping the IP address, the output "IP can communicate"
If the computer cannot ping the IP address, the output "IP can not communicate"
[Email protected] ~]# cat/root/6.sh
#!/bin/bash
Read-p ' Please enter the IP address you want to test: ' IP
Ping-c 2 $ip &>/dev/null #ping测试2包结束
If [$?-eq 0];then
echo $ip can communicate
Else
Echo $ip can not communicate
Fi
#################################################
If multi-branch processing
If [condition test 1]; Then
Command sequence XX
elif [condition Test 2]; Then
Command Sequence yy
Else
Command Sequence ZZ
Fi
##################################################
To write a script, implement
Read student scores with read
Greater than or equal to 90 output excellent
Greater than or equal to 80 output good
Greater than or equal to 60 output qualified
The above conditions are not satisfied
Output still requires effort
[Email protected] ~]# vim/root/7.sh
#!/bin/bash
Read-p ' Please enter your score: ' num
If [$num-ge];then #判断是否大于等于90
Echo Excellent
elif [$num-ge];then #判断是否大于等于80
echo Good
elif [$num-ge];then #判断是否大于等于60
Echo qualified
Else
Echo still needs to work hard
Fi
#####################################################
Create a/root/foo.sh script on Server0
1) When running/root/foo.sh Redhat, the output is Fedora
2) When running/root/foo.sh fedora, output is Redhat
3) when no parameters or parameters are not redhat or
When fedora, its error output produces the following information:
/root/foo.sh Redhat|fedora
[Email protected] ~]# vim/root/foo.sh
#!/bin/bash
If [$#-eq 0];then #判断是否有位置变量
Echo '/root/foo.sh Redhat|fedora ' >&2 #将正确的输出变成错误
Exit 1 #脚本运行后返回值
elif [= = Redhat];then
echo Fedora
elif [= = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora ' >&2 #将正确的输出变成错误
Exit 1 #脚本运行后返回值
Fi
[Email protected] ~]#/root/foo.sh
[[email protected] ~]# echo $?
#########################################################
For loop structure
For haha in Zhangsan Lisi Wangwu Tianqi
Do
Useradd $haha
Done
[Email protected] opt]# vim/root/for.sh
#!/bin/bash
For i in stu01 stu02 stu03 stu04
Do
Useradd $i
Echo $i created successfully
Done
Shell Script Basics