bash脚本编程:
if语句、bash -n、bash -x
CONDITION:
bash命令:
用命令的执行状态结果:
成功true
失败flase
成功或失败的意义:取决于用到的命令
单分支:
if CONDITION;then
if-true
fi
双分支:
if CONDITION;then
if-true
else
if-true
fi
多分支:
if CONDITION1;then
if-true
elif CONDITION1;then
if-true
...
else
all-false
fi
逐条进行判断,第一次遇到为真是,执行器分支,而后结束
注意: if语句可以嵌套
判断文件类型脚本
#!/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
bash -n filename #检测语法
-x #逐条执行
循环:for,while,unitl
循环体:
进入条件;
退出条件
for循环:
for 变量名 in 列表;do
循环体
done
执行机制:
一次将列表中的元素赋给"变量名";每次赋值后即执行一次循环体;只掉列表中的元素耗尽,循环结束
列表生成方式:
(1)直接给出字符串列表;
(2)整数列表
(a) {start..end}
(b)$(seq [start] [step]] end )
(3) 返回列表的命令:
$(COMMAND)
如:$(ls /etc)
#!/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"