几个shell小脚本
1.求100以內偶數和
#!/bin/bash
let I=1
let SUM=0
while [ $I -le 100];do
if [ (($I%2))-eq 0 ]
then
SUM=$(($SUM+$I))
I=$(($I+1))
else
I=$(($I+1))
fi
done
echo "The sum is :$SUM"
2.求三個數中的最大值
#!/bin/bash
echo? "please enter three number:"
read A B C
if [ $A -gt $B ]
then
max=$A
else max=$B
fi
if [ $C -gt $max ]
then
max=$C
fi
echo "The max is $max"
3.顯示登錄用戶時間,用戶名
#!/bin/bash
cat /etc/passwd|cut -d:? -f1|grep '^$1\>' ||who |grep $1? &> /dev/null
if [ $? -eq 0 ];then
echo "the user is :$1"
TIME=`who|cut -d- -f2,3|cut -d' ' -f1,2`
COUNT=`who |grep $1 |cut -d' ' -f1|wc -l`
echo "$1 login counts are:$COUNT"
echo "$1 login time is:$TIME"
else
echo "please give me a current name:"
fi
4.ping 一個c類網
?#!/bin/bash
? cping (){
? pingnet=`echo $1 | sed 's/\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\).*\1/g'`
? let I=1
?? while [ $I -le 254 ];do
?? ping -c 1 -W 2 $pingnet.$I &> /dev/null
?? [ $? -eq 0 ] && echo "$pingnet.$I online." || echo "$pingnet.$I offline."
?? let I++
?? done
? }
? read -p "A network:"MYNET
? cping $MYNET
5.判斷用戶是否存在并顯示默認shell
#!/bin/bash
read? -p "please input your username:" A
?if cut -d: -f1 /etc/passwd |grep "^$A$" &> /dev/null;then
B=`grep "$A:"?? /etc/passwd | cut -d: -f7`
echo "${A}'s shell is $B."?
?else
?? echo " $A not exist,please give me a correct username! "
?fi
6.輸入一個文件并統計有多少行
#!/bin/bash
let COUNTS=0
echo "Please enter a file:"FILE
read FILE
if [ -e $FILE -a -f $FILE ];then
?
?while read LINE
?
?do
?
?echo $LINE
?
?COUNTS=$(($COUNTS+1))
?
?done < $FILE
?
?echo "The total linesis $COUNTS."
else
echo? "This FILE is wrong ,please enter a right FILE. "
?
fi
7.定義一個簡單的函數,求兩個數的大小
#!/bin/bash
max() {
[ $1 -gt $2 ] && echo "The max is $1."||echo "The max is $2."
}
max 1 2
?
轉載于:https://blog.51cto.com/chenxizhuimeng/459296
總結
以上是生活随笔為你收集整理的几个shell小脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows的几个原则
- 下一篇: ^_^ 一看就忘不了的IE页面 ^_^