4.2 编写Shell脚本 /Page:80
①、交互式(Interactive):用户每输入一条命令就立即执行。
②、批处理(Batch):由用户事先编写好一个完整的 Shell 脚本, Shell 会一次性执行脚本中诸多的命令。
4.2.1 编写简单的脚本
#! /bin/bash {脚本声明}
#Linux {脚本注释}
pwd {脚本命令}
ls {脚本命令}
uptime {脚本命令}
4.2.2 接收用户的参数
EX.:
[root@linuxprobe ~]# vim example.sh
#! /bin/bash
echo "当前脚本名称为
0
"
e
c
h
o
"
总
共
有
0" echo "总共有
0"echo"总共有#个参数,分别是$*。 "
echo "第 1 个参数为$1,第 5 个为$5。 "
[root@linuxprobe ~]# sh example.sh one two three four five six
当前脚本名称为 example.sh
总共有 6 个参数,分别是 one two three four five six。
第 1 个参数为 one,第 5 个为 five。
4.2.3 判断用户的参数
①、命令A && 命令B|【“与”运算,当命令A执行成功后才会执行命令B】
②、命令A || 命令B|【“或”运算,当命令A执行失败后才会执行命令B】
③、!命令|【“非”运算,把条件测试中的判断结果取相反值】
EX.:内存阈值提醒
4.3 流程控制语句 /Page:85
4.3.1 if条件测试语句
EX:
[root@linuxprobe ~]# vim mkcdrom.sh
#!/bin/bash
DIR="/media/cdrom"
if [ ! -e $DIR ]
then
mkdir -p $DIR
fi
EX.:
[root@linuxprobe ~]# vim chkhost.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo “Host $1 is On-line.”
else
echo “Host $1 is Off-line.”
fi
EXC. and OUT.:
[root@linuxprobe ~]# bash chkhost.sh 192.168.10.10
Host 192.168.10.10 is On-line.
[root@linuxprobe ~]# bash chkhost.sh 192.168.10.20
Host 192.168.10.20 is Off-line.
EX.:
[root@linuxprobe ~]# vim chkscore.sh
#!/bin/bash
read -p “Enter your score(0-100): " GRADE
if [ $GRADE -ge 85 ] && [
G
R
A
D
E
−
l
e
100
]
;
t
h
e
n
e
c
h
o
"
GRADE -le 100 ] ; then echo "
GRADE−le100];thenecho"GRADE is Excellent”
elif [ $GRADE -ge 70 ] && [
G
R
A
D
E
−
l
e
84
]
;
t
h
e
n
e
c
h
o
"
GRADE -le 84 ] ; then echo "
GRADE−le84];thenecho"GRADE is Pass"
else
echo “$GRADE is Fail”
fi
EXC. and OUT.:
[root@linuxprobe ~]# bash chkscore.sh
Enter your score(0-100): 88
88 is Excellent
[root@linuxprobe ~]# bash chkscore.sh
Enter your score(0-100): 80
80 is Pass
4.3.2 for条件循环语句
EX.:
[root@linuxprobe ~]# vim Example.sh
#!/bin/bash
read -p “Enter The Users Password : " PASSWD
for UNAME in cat users.txt
do
id $UNAME &> /dev/null
if [ $? -eq 0 ]
then
echo “Already exists”
else
useradd KaTeX parse error: Expected 'EOF', got '&' at position 7: UNAME &̲> /dev/null ech…PASSWD” | passwd --stdin $UNAME &> /dev/null
if [
?
−
e
q
0
]
t
h
e
n
e
c
h
o
"
? -eq 0 ] then echo "
?−eq0]thenecho"UNAME , Create success"
else
echo “$UNAME , Create failure”
fi
fi
done
4.3.3 while条件循环语句
课堂笔记截图