求1-100自然数的和:
法一:for循环
#!/bin/bash
#
declare -i sum=0
for ((i=0;i<=100;i++));do
let sum+=$i
done
echo "Sum:$sum"
法二:while循环
#!/bin/bash
#
declare -i sum=0
declare -i i=0
while [ $i -le 100 ];do
let sum+=$i
let i++
done
echo $i
echo "Summary:$sum."
统计tcp连接状态的脚本:
#!/bin/bash
# This script is count tcp status
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 "Unknow:$other"
批量添加10个用户:
#!/bin/bash
if [ ! $UID -eq 0 ];then
echo "Only root can use this script."
exit 1
fi
for i in {1..10};do
if id user$i &> /dev/null;then
echo "user$i exist"
else
useradd user$i
if [ $? -eq 0 ];then
echo "user$i" | passwd --stdin user$i &> /dev/null
fi
fi
done
测试一个网段内主机的连通脚本:
#!/bin/bash
#ping
net='172.16.1'
uphosts=0
downhosts=0
for i in {1..254};do
ping -c 1 -w 1 ${net}.${i} &> /dev/null
if [ $? -eq 0 ];then
echo "${net}.${i} is up."
let uphosts++
else
echo "${net}.${i} is down."
let downhosts++
fi
done
echo "Up hosts:$uphosts"
echo "Down hosts:$downhosts"
求数的阶乘:
#!/bin/bash
#
fact() {
if [ $1 -eq 0 -o $1 -eq 1 ];then
echo 1
else
echo $[$1*$(fact $[$1-1])]
fi
}
fact 5