1. 程式人生 > >shell腳本小示例

shell腳本小示例

amp logs -1 done int oot 階乘 i++ blog

求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

                          

  

shell腳本小示例