码迷,mamicode.com
首页 > 系统相关 > 详细

shell脚本小示例

时间:2017-10-12 17:08:41      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:grep   null   exist   count   连接状态   only   blog   pass   bin   

求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脚本小示例

标签:grep   null   exist   count   连接状态   only   blog   pass   bin   

原文地址:http://www.cnblogs.com/pythonal/p/7656576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!