bash脚本编程:
if语句、bash -n、bash -x
CONDITION:
bash命令:
用命令的执行状态结果;
成功:true
失败:flase
成功或失败的意义:取决于用到的命令;
单分支:
if CONDITION; then
if-true
fi
双分支:
if CONDITION; then
if-true
else
if-false
fi
多分支:
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
...
esle
all-false
fi
逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束;
示例:用户键入文件路径,脚本来判断文件类型;
#!/bin/bash
#
read -p "Enter a file path: " filename
if [ -z "$filename" ]; then
echo "Usage: Enter a file path."
exit 2
fi
if [ ! -e $filename ]; then
echo "No such file."
exit 3
fi
if [ -f $filename ]; then
echo "A common file."
elif [ -d $filename ]; then
echo "A directory."
elif [ -L $filename ]; then
echo "A symbolic file."
else
echo "Other type."
fi
注意:if语句可嵌套;
循环:for, while, until
循环体:要执行的代码;可能要执行n遍;
进入条件:
退出条件:
for循环:
for 变量名 in 列表; do
循环体
done
执行机制:
依次将列表中的元素赋值给“变量名”; 每次赋值后即执行一次循环体; 直到列表中的元素耗尽,循环结束;
示例:添加10个用户, user1-user10;密码同用户名;
#!/bin/bash
#
if [ ! $UID -eq 0 ]; then
echo "Only root."
exit 1
fi
for i in {1..10}; do
if id user$i &> /dev/null; then
echo "user$i exists."
else
useradd user$i
if [ $? -eq 0 ]; then
echo "user$i" | passwd --stdin user$i &> /dev/null
echo "Add user$i finished."
fi
fi
done
列表生成方式:
(1) 直接给出列表;
(2) 整数列表:
(a) {start..end}
(b) $(seq [start [step]] end)
(3) 返回列表的命令;
$(COMMAND)
(4) glob
(b) 变量引用;
$@, $*
示例:判断某路径下所有文件的类型
#!/bin/bash
#
for file in $(ls /var); do
if [ -f /var/$file ]; then
echo "Common file."
elif [ -L /var/$file ]; then
echo "Symbolic file."
elif [ -d /var/$file ]; then
echo "Directory."
else
echo "Other type."
fi
done
示例:
#!/bin/bash
#
declare -i estab=0
declare -i listen=0
declare -i other=0
for state in $( netstat -tan | grep "^tcp\>" | awk ‘{print $NF}‘); do
if [ "$state" == ‘ESTABLISHED‘ ]; then
let estab++
elif [ "$state" == ‘LISTEN‘ ]; then
let listen++
else
let other++
fi
done
echo "ESTABLISHED: $estab"
echo "LISTEN: $listen"
echo "Unkown: $other"
练习1:/etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的文件;
分别读取每个文件,以K开头的文件输出为文件加stop,以S开头的文件输出为文件名加start;
“K34filename stop”
“S66filename start”
练习2:写一个脚本,使用ping命令探测172.16.250.1-254之间的主机的在线状态;
本文出自 “梁小明的博客” 博客,请务必保留此出处http://7038006.blog.51cto.com/7028006/1829381
原文地址:http://7038006.blog.51cto.com/7028006/1829381