Table of contents
Basic introduction to shell script applications
1. Shell script
1. The role of shell script and the role of shell interpreter
2. The basic structure of the script and the way to execute it
3. Pipe characters and reshaped basic input and output
2. Basic use of environment variables
1. Type of variable
2. Configure custom variables
3. Common symbols for variable assignment
4. Integer variable operator
5. Special variables
Shell script application basic operations
1. Condition test
1. Test judgment
2. Comparison operators
3. String comparison
4. Logic test
2. if judgment
1. Type of if judgment
2. Single branch if judgment
3. Double-branch judgment
4. Multi-branch if judgment
Application of shell script
1. Basic use of loops
1. for loop
2. while random loop
Two basic applications of case control services
1. The syntax format of case
2. Use case to write a script to control vsftpd service
Basic introduction to shell script applications
1. Shell script
1. The role of shell script and the role of shell interpreter
1) The role of shell script
Automated operation and maintenance use
Batch repeated operations using scripts instead
2) The role of the shell interpreter
The bash command interpreter used by default in Linux systems
Responsible for receiving user input commands and submitting them to the CPU for judgment and execution.
2. The basic structure of the script and the way to execute it
1) The structure of the script
[root@centos01 ~]# vim test.sh |
Script suffix file *.sh |
#!/bin/bash |
statement |
#E-mail:[email protected] |
Description of the script and contact information for writing the script |
Script execution command |
2) How to run the script
[root@centos01 ~]# sh test.sh |
Run using sh command |
[root@centos01 ~]# ./test.sh |
Run script at current location |
[root@centos01 ~]# source ./test.sh |
source command to run script |
3. Pipe characters and reshaped basic input and output
1) Basic input and output
Standard input: receiving or reading data entered by the user<
Standard output: display data on the screen or in a file >, append >>
Error output: Error output can be displayed on the screen or in a specific file, 2> Error output
Mixed output: output to the file regardless of whether it is correct or incorrect,&>
2) Pipe character |
Turn the result of the previous command execution into the object processed by the next command.
2. Basic use of environment variables
1. Type of variable
1) Custom variables
The administrator creates it manually and defines it as needed.
2) Environment variables
Maintain system usage
No administrator is required to create the system to create it automatically
3) Position variable
Use the command line to pass program parameters to the script.
4) Predefined variables
bash predefined special variables
User cannot modify
2. Configure custom variables
1) Create a variable, the variable name is a variable value is 10
[root@centos01 ~]# a=10
2) Two ways to view variable values
[root@centos01 ~]# echo $a
[root@centos01 ~]# expr $a
3. Common symbols for variable assignment
1) Double quotes, allowing other variable values to be quoted through the $ symbol
[root@centos01 ~]# test="$ab $bb"
[root@centos01 ~]# echo $test
benet 6.0
2) Single quotes, it is forbidden to quote other variable values
[root@centos01 ~]# test='$ab $bb'
[root@centos01 ~]# echo $test
$ab $bb
3) Reverse, command substitution to extract the results of command execution
[root@centos01 ~]# aa=`netstat -anptu | grep 22`
[root@centos01 ~]# echo $aa
4) read assigns the input content to a specific variable name
[root@centos01 ~]# read -p "Please enter a specific directory:" insert
Please enter a specific directory:/boot
[root@centos01 ~]# echo $insert
/boot
5) Define global environment variables that subshells can apply
[root@centos01 ~]# export a=100
[root@centos01 ~]# echo $a
4. Integer variable operator
1) Created operator
+: addition
-: Subtraction
\*:multiplication
/:division
%: Modulo (remainder) operation
2) Basic applications of computing
[root@centos01 ~]# a=100
[root@centos01 ~]# b=200
[root@centos01 ~]# expr $a + $b
300
[root@centos01 ~]#expr 1 + 1
[root@centos01 ~]#echo $[1+1]
[root@centos01 ~]#echo “scale=2;1.25*1.25”|bc
[root@centos01 ~]#free
[root@centos01 ~]#vim mom.sh
#!/bin/bash
mt=$(free | awk 'NR==2{print $2}')
mu=$(free | awk 'NR==2{print $3}')
muu=$(expr $mu \* 100 / $mt)
echo $muu
or
echo "scale=2; $mu/$mt*100" |bc
[root@centos ~]# free | awk 'NR==2{print int($3/$2*100)"%"}'
3) Curly braces are used to distinguish symbols
[root@centos01 ~]# echo ${ab}0.10.1
benet0.10.1
5. Special variables
1) Environment variables
System creation
2) Position variable
Provide 9 positions $n (n represents 1--9)
3) Predefined variables
$#: Positional parameters in the command line
$*: all positional parameters
$?: The recorded script execution status 0 indicates success, non-0 indicates error
$0: The name of the process program that executes the script
[root@centos ~]# vim bak.sh
#!/bin/bash
mkdir /backup
tar zcf /backup/file_all-$(date +%F).tar.gz $* &>/dev/null
echo "共备份了$#个文件"
echo "成功执行了$0脚本"
echo "备份的文件为:$*"
or
[ $? -eq 0] && echo "$0 script successfully executed"
[root@centos ~]# chmod +x bak.sh
[root@centos ~]# ./bak.sh /etc/passwd /etc/group
Clear rebuild cache
yum clean all && yum makecache fast
挂载光盘
#!/bin/bash
#用户自动构建yum仓库脚本
#挂载光盘
mount /dev/cdrom /mnt
#创建仓库文件
cd /etc/yum.repos.d/
mkdir bak
mv *.repo bak
#创建yum文件
echo “[yum]
name=yum
baseurl=file:///mnt
enabled=1
gpgcheck=0” > local.repo
# 清除重建缓存
yum clean all && yum makecache fast
Batch processing of unified file contents --- non-interactive
vi pass.txt
123456
#useradd user1
#passwd --stdin user1 < pass.txt
或者
#echo “123456” | passwd --stdin user1
&> or 2>&1, &>some syntax is not supported
vim /etc/init.d/network
Mounting disc prompt information redirects to black hole
#!/bin/bash
#用户自动构建yum仓库脚本
echo “挂载光盘…..”
mount /dev/cdrom /mnt &> /dev/null
echo “创建仓库文件…..”
cd /etc/yum.repos.d/
mkdir bak
mv *.repo bak
#创建yun文件
echo “[yum]
name=yum
baseurl=file:///mnt
enabled=1
gpgcheck=0” > local.repo
echo “清除重建缓存…..”
yum clean all &> /dev/null && yum makecache fast &> /dev/null
echo “yum创建成功….”
#cd /boot | ls –l
#cd /boot ; ls –l
#ls /etc | wc -l
#find ./ -name “*.sh” | xargs ls -l xargs force reception
#cat 123
11 22 33
aa bb cc
#awk ‘{print $2}’first.sh
#awk ‘ {print $2}’123
#awk ‘{print $2,$1,$3}’123
#df
#df |grep “/$”| awk ‘{print $5}’
#df |grep “/$”| awk ‘{print $5}’| awk –F ‘%’ ’{print $1}’
or
# df | awk –F’[ %]+’ ’/\/$/{print $(NF-1)}’
#x=18
#expr 3 + $x
variable
#!/bin/bash
#用户自动构建yum仓库脚本
x=”/mnt”
echo “挂载光盘…..”
mount /dev/cdrom $x &> /dev/null
echo “创建仓库文件…..”
cd /etc/yum.repos.d/
mkdir bak
mv *.repo bak
#创建yun文件
echo “[yum]
name=yum
baseurl=file://$x
enabled=1
gpgcheck=0” > local.repo
echo “清除重建缓存…..”
yum clean all &> /dev/null && yum makecache fast &> /dev/null
echo “yum创建成功….”
rpm –qi $(rpm –qf $(which mkdir))
variable output
#name=zhangsan
#echo $name
#echo ${name}
#echo $intended
#echo ${name}nihao
read -p "Please enter your name : " name
echo $name
variable
#!/bin/bash
#用户自动构建yum仓库脚本
read -p “输入你的挂载点位置:” x
echo “挂载光盘…..”
mkdir $x
mount /dev/cdrom $x &> /dev/null
echo “创建仓库文件…..”
cd /etc/yum.repos.d/
mkdir bak
mv *.repo bak
#创建yun文件
echo “[yum]
name=yum
baseurl=file://$x
enabled=1
gpgcheck=0” > local.repo
echo “清除重建缓存…..”
yum clean all &> /dev/null && yum makecache fast &> /dev/null
echo “yum创建成功….”
user-interface
#!/bin/bash
echo “centos….
kernel….”
read –p “localhost login:”user
if [ $user = “root”]
then
echo “欢迎登陆”
else
echo “拜拜”
fi
Shell script application basic operations
1. Condition test
1. Test judgment
1) Determine the result type
real
Fake
2) Judgment grammar
[root@centos01 ~]# test -d /boot && echo "YES" |
The test boot directory shows YES |
[root@centos01 ~]# [ -d /boot ] && echo "yes" |
The test boot directory shows YES |
3) Common testing options
-d test directory
-f test file
-w tests write permissions
-r tests read permission
-x tests execution permissions
-e tests whether the file directory exists
[root@centos ~]# vim cd.sh
#!/bin/bash
[ -d /cd ] || mkdir /cd
[ -d /cd/Packages ] || mount /dev/cdrom /cd &> /dev/null
2. Comparison operators
1) Common comparison operators
gt is greater than
lt is less than
ge is greater than or equal to
le is less than or equal to
eq is equal to
ne is not equal to
[root@centos ~]# vim num.sh
#!/bin/bash
read -p "Please enter a number:" num
[ $(expr $num % 2) -eq 0 ] && echo "$num is an even number" || echo "$num is a base number"
[root@centos ~]# sh num.sh
Please enter a number: 123
123 is the base number
2) Basic use of comparison operators
[root@centos01 ~]# [ 10 -gt 5 ] && echo "YES" |
10 greater than 5 is displayed as yes |
[root@centos01 ~]# abc=`history | wc -l` [root@centos01 ~]# [ $abc -gt 100 ] && echo "yes" |
Extract the history command line number, compare it with 100 and display yes if it is greater than 100 |
3. String comparison
1) String comparison operator
=: Whether the string contents are the same
!=: Whether the string contents are different
-z: Check if the string is empty
2) Application of string comparison, strings need to use double quotes
[root@centos01 ~]# [ "aaa" = "aaa" ] && echo "yes" |
Determine whether all aaa characters are equal to aaa characters |
[root@centos01 ~]# [ $LANG != "en.US" ] && echo "Chinese is not supported!!" |
LANG variable is not equal to en.US display does not support Chinese |
4. Logic test
1) Common operators for logic testing
&&: And or expressed with -a, the two results are displayed if they are true.
||: Or, or use -o to indicate that the two judgment results only need to meet one condition to be displayed as true.
!: No, it is true if the two judgment results are not established.
[root@centos ~]# vim cj.sh
#!/bin/bash
read -p "Enter test scores:" num
[ $num -ge 60 -a $num -le 100 ] && echo "passed the exam"
or
[ $num -ge 60 ] && [ $num -le 100 ] && echo "passed the exam"
2) Logic test is simple to use
[root@centos01 ~]# [ -d /etc ] && [ -d /boot ] && echo "It is a directory!!" |
If both results are true, the display is a directory. |
[root@centos01 ~]# [ -d /etc ] || [ -d /ssss ] && echo "It is a directory!!" |
If one of the two results is true, it is displayed as a directory. |
2. if judgment
1. Type of if judgment
1) Single branch
Conditions are met to execute the command sequence
2)Double branch
Execute the first command sequence when the conditions are met
Execute the second command sequence if the conditions are not met
3) Multiple branches
Execute the first command sequence when the conditions are met
If the condition does not meet the first condition and the second condition is matched, the second command sequence is executed.
If the second condition is not met, the last condition is executed and the default command sequence is run.
2. Single branch if judgment
1) Single-point if judgment command structure
if [condition]
Then
Execute command sequence
fi
2) Test whether the directory exists. If it does not exist, it will be automatically created. If the directory exists, stop executing the script.
#!/bin/bash
mount="/mnt/test"
if [ ! -d $mount ]
then
mkdir -p $mount
Fi
3) Test disk space
[root@centos01 ~]# export aa=`df -Th | grep "/$" | awk '{print $5}' |awk –F “%” ‘{pring $1}’` |
Extract disk space |
[root@centos01 ~]# cat fdisk.sh #!/bin/bash if [ $aa -eq 73 ] then echo "The disk is full and cannot store data!!!" fi [root@centos01 ~]# |
The extracted disk space is equal to 73G to remind the user that data cannot be stored. |
[root@centos ~]# vim disk.sh
#!/bin/bash
du=$(df | grep "/$" | awk '{print $5}' | awk -F'%' '{print $1}')
if [ $du -gt 3 ]
then
echo "Use exceeds"
fi
3. Double-branch judgment
1) Multi-branch command structure
if [condition]
then
Execute command sequence one
else
Execute command sequence two
Fi
1. Whether the httpd service is started?
[root@centos ~]# vim httpd.sh
#!/bin/bash
netstat -lnpt | grep -q :80
if [ $? -eq 0 ]
then
echo "Website service is running"
else
echo "Service is closed, try to start"
systemctl start httpd
fi
[root@centos ~]# bash httpd.sh
2. Determine whether the bind package is installed
[root@centos ~]# vim bind.sh
#!/bin/bash
rpm -q bind &> /dev/null
if [ $? -eq 0 ]
then
echo "The package is installed"
else
echo "The package is not installed, try to install it"
yum -y install bind &> /dev/null
[ $? -eq 0 ] && echo "Software installation successful"
fi
[root@centos ~]# bash bind.sh
2) Determine whether the host is communicating
[root@centos01 ~]# cat ./ping.sh
#!/bin/bash
read -p "Please enter the specified IP address:" ping
ping -c 3 -i 0.2 -W 3 $ping &> /dev/null
if [ $? -eq 0 ]
then
echo "host is $ping UP!!!!"
else
echo "host is $ping DOWN!!!!"
fi
or
[root@centos ~]# vim ping.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "host $1 is up"
else
echo "host $1 is down"
fi
[root@centos ~]# chmod +x ping.sh
[root@centos ~]# ./ping.sh
[root@centos ~]# ./ping.sh 192.168.200.1
4. Multi-branch if judgment
1) Multi-branch if judgment grammatical structure
if [conditional judgment]
then
Execute command sequence one
elif [conditional judgment]
then
Execute command sequence two
else
Execute command sequence three
2) Write multi-branch test scripts
Normal statement to judge whether the score is qualified or not - there are loopholes
#!/bin/bash
read -p "Enter the test score range 1~100 points:" test
if [ $test -ge 85 ] && [ $test -le 100 ]
then
echo "$test points, you are awesome and did well in the exam!!!"
elif [ $test -ge 70 ] && [ $test -le 84 ]
then
echo "$test points, you need to continue working hard to pass the exam!!!"
else
echo "$test points, you need to study again!!!"
fi
or
#!/bin/bash
read -p "Enter the test score range 1~100 points:" test
if [ $test -ge 0 -a $test -le 100 ]
then
if [ $test -ge 85 -a $test -le 100 ]
then
echo "$test points, you are awesome and did well in the exam!!!"
elif [ $test -ge 70 -a $test -le 84 ]
then
echo "$test points, you need to continue working hard to pass the exam!!!"
else
echo "$test points, you need to study again!!!"
fi
else
echo "The score is wrong and cannot be judged"
fi
rock-paper-scissors
[root@centos ~]# vim games.sh
#!/bin/bash
echo "This is a small game of (Rock 0 Scissors 1 Paper 2), relax:"
pc=$(expr $RANDOM % 3)
read -p "Enter your choices:" user
if [ $pc -eq 0 -a $user -eq 2 ] || [ $pc -eq 1 -a $user -eq 0 ] || [ $pc -eq 2 -a $user -eq 1 ]
then
echo "Congratulations on winning the computer"
elif [ $pc -eq $user ]
then
echo "draw"
else
echo "You lose, come again"
fi
~
or
#!/bin/bash
echo "This is a small game of (Rock 0 Scissors 1 Paper 2), relax:"
while true
do
pc=$(expr $RANDOM % 3)
read -p "Enter your choices:" user
if [ $pc -eq 0 -a $user -eq 2 ] || [ $pc -eq 1 -a $user -eq 0 ] || [ $pc -eq 2 -a $user -eq 1 ]
then
echo "Congratulations on winning the computer"
elif [ $pc -eq $user ]
then
echo "draw"
else
echo "You lose, come again"
fi
done
Application of shell script
1. Basic use of loops
1. for loop
1) Grammatical structure of for loop
for variable name in value list
do
command sequence
done
2) Definition of for list
[root@centos01 ~]# cat username.txt
bob
tom
alice
3) Create a for loop to create users in batches and set the password to 123456
#!/bin/bash
for name in $(cat user.txt)
do
useradd $name
echo "123456" | passwd --stdin $name
done
4) Delete users in batches
#!/bin/bash
for name in $(cat user.txt)
do
userdel -r $name
done
5) Use a for loop to ping the host that the user wants to access
#!/bin/bash
for ip in $(cat p.txt)
do
ping -c 3 -i 0.2 -W 3 $ip &> /dev/null
if [ $? -eq 0 ]
then
echo "host $ip is up"
else
echo "host $ip is down"
fi
done
[root@centos ~]# for i in {10..1};do echo $i;sleep 1;done
round robin rules
#!/bin/bash
for i in {1..9}
do
for j in {1..9}
do
echo $i $j
done
done
multiplication table
#!/bin/bash
for i in {1..9}
do
for ((j=1;j<=$i;j++))
do
echo -n "${j}x${i}=$(($i*$j)) "
done
echo
done
2. while random loop
1) Command structure of while
while [condition]
do
command sequence
done
2) Randomly create 20 accounts with passwords set to 123456
[root@centos01 ~]# cat aaa.sh
#!/bin/bash
i=1
while [ $i -le 20 ]
do
userdel -r stu$i
#useradd stu$i
#echo "123456" | passwd --stdin stu$i
let i++
Done
Games time
Guess the number
#!/bin/bash
echo "This is a small game to guess the product price (1-1000), guess"
pc=$(expr $RANDOM % 1000 + 1)
cs=0
while true
do
read -p "Enter your guessed price:" int
let cs++
if [ $int -gt $pc ]
then
echo "The price is too high"
elif [ $int -eq $pc ]
then
echo "Congratulations on guessing correctly"
echo "Guessed $cs times in total"
exit
else
echo "The price is too low"
fi
done
Two basic applications of case control services
1. The syntax format of case
case variable value in
Mode 1)
;;
Mode 2)
;;
*)
Default command sequence
esac
2. Use case to write a script to control vsftpd service
[root@centos01 ~]# cat ./vsftpd.sh
#!/bin/bash
#chkconfig:35 80 21
#Description:vsftpd Server
case "$1" in
start)
echo "Starting vsftpd service [OK]"
;;
stop)
echo "Stop vsftpd service [OK]"
;;
restart)
echo "Restarting vsftpd service [OK]"
;;
*)
echo "Usage:$0{start|stop|restart}"
esac
[root@centos01 ~]#
example:
[root@centos ~]# vim /etc/init.d/file
#!/bin/bash
case $1 in
create)
touch /tmp/{1..100}.txt
;;
delete)
rm -rf /tmp/{1..100}.txt
;;
list)
ls -l /tmp/{1..100}.txt
;;
*)
echo "用法:$0{create|delete|list}"
esac
Example :
#!/bin/bash
read -p "Please enter a character:" str
case $str in
[a-zA-Z])
echo "letter"
;;
[0-9])
echo "number"
;;
*)
echo "Special symbols"
esac