自己常用的一些shell脚本分享
自己写了一下小的shell实例,虽然很小,但所有的大的程序都是由小的模块堆积起来的,程序员一定要懂得一种脚本的书写,而我,只会在linux下工作,所以就只能写linux的shell脚本了,呵呵,本文会陆续更新,给自己加油!
1.模拟linnux登录shell
#/bin/bash echo-n"login:" readname echo-n"password:" readpasswd if[$name="cht"-a$passwd="abc"];then echo"thehostandpasswordisright!" elseecho"inputiserror!" fi
2.比较两个数大小
#/bin/bash echo"pleaseentertwonumber" reada readb iftest$a-eq$b thenecho"NO.1=NO.2" eliftest$a-gt$b thenecho"NO.1>NO.2" elseecho"NO.1<NO.2" fi
3.查找/root/目录下是否存在该文件
#/bin/bash echo"enterafilename:" reada iftest -e/root/$a thenecho"thefileisexist!" elseecho"thefileisnotexist!" fi
4.for循环的使用
#/bin/bash clear fornumin12345678910 do echo"$num" done
5.
#/bin/bash echo"Pleaseenterauser:" reada b=$(whoami) iftest$a=$b thenecho"theuserisrunning." elseecho"theuserisnotrunning." fi
6.删除当前目录下大小为0的文件
#/bin/bash
forfilenamein`ls`
do
iftest-d$filename
thenb=0
else
a=$(ls-l$filename|awk'{print$5}')
iftest$a-eq0
thenrm$filename
fi
fi
done
7.如果/export/um_lpp_source下有文件,那么将其文件系统大小改为3G
#/bin/bash
whileline=`ls/export/um_lpp_source`
do
iftest$line=""
then echo"NULL"
sleep1
elseecho$line
chfs-asize=3G/export/um_lpp_source
exit0
fi
done
8.测试IP地址
#/bin/bash foriin 123456789 do echo"thenumberof$icomputeris" ping-c1192.168.0.$i done
9.如果test.log的大小大于0,那么将/opt目录下的*.tar.gz文件
#/bin/sh
a=2
whilename="test.log"
do
sleep1
b=$(ls-l$name|awk'{print$5}')
iftest$b-ge$a
#thenecho"OK"
then`cp/opt/*.tar.gz.`
exit0
fi
done
10.打印读取的内容,为下面的例子做准备
#/bin/bash whilereadname do echo$name done
11.从0.sh中读取内容并打印
#/bin/bash whilereadline do echo$line done<0.sh
12.读取a.c中的内容并做加1运算
#/bin/bash test-ea.c whilereadline do a=$(($line+1)) done<a.c echo$a
13.普通无参数函数
#/bin/bash
p()
{
echo"hello"
}
p
14.给函数传递参数
#/bin/bash
p_num()
{
num=$1
echo$num
}
fornin$@
do
p_num$n
done
15.创建文件夹
#/bin/bash
while:
do
echo"pleaseinputfile'sname:"
reada
iftest-e/root/$a
then
echo"thefileisexistingPleaseinputnewfilename:"
else
mkdir$a
echo"youayesussesful!"
break
fi
done
16.获取本机IP地址
#/bin/bash
ifconfig|grep"inetaddr:"|awk'{print$2}'|sed's/addr://g'
17.查找最大文件
#/bin/bash
a=0
for namein*.*
do
b=$(ls-l$name|awk'{print$5}')
iftest$b-ge$a
thena=$b
namemax=$name
fi
done
echo"themaxfileis$namemax"
18.查找当前网段内IP用户,重定向到ip.txt文件中
#/bin/bash
a=1
while:
do
a=$(($a+1))
iftest$a-gt255
thenbreak
else
echo$(ping-c1192.168.0.$a|grep"ttl"|awk'{print$4}'|sed's/://g')
ip=$(ping-c1192.168.0.$a|grep"ttl"|awk'{print$4}'|sed's/://g')
echo$ip>>ip.txt
fi
done
19.打印当前用户
#/bin/bash
echo"CurrentUseris:"
echo$(ps|grep"$$"|awk'{print$2}')
20.case语句练习
#!/bin/bash clear echo"enteranumberfrom1to5:" readnum case$numin 1)echo"youenter1" ;; 2)echo"youenter2" ;; 3)echo"youenter3" ;; 4)echo"youenter4" ;; 5)echo"youenter5" ;; *)echo"error" ;; esac
21.yes/no返回不同的结构
#!/bin/bash clear echo"enter[y/n]:" reada case$ain y|Y|Yes|YES)echo"youenter$a" ;; n|N|NO|no)echo"youenter$a" ;; *)echo"error" ;; esac
22.内置命令的使用
#/bin/bash
clear echo"Hello,$USER" echo echo"Today'sdateid`date`"
echo
echo"theuseris:" who echo
echo"thisis`uname-s`" echo
echo"that'sallfolks!"