配色: 字号:
linux shell 实例
2013-11-05 | 阅:  转:  |  分享 
  
1.写一个脚本,利用循环计算10的阶乘





#!/bin/sh



factorial=1



forain`seq110`

do

factorial=`expr$factorial\$a`

done



echo"10!=$factorial"



注:上面有一行,forain`seq110`,其中seq110,即列出现1到10之间所有的数字,这一行也可改为:forain"12345678910"

2.写一个脚本,执行后,打印一行提示“Pleaseinputanumber:",要求用户输入数值,然



后打印出该数值,然后再次要求用户输入数值。直到用户输入



"end"停止。





#!/bin/sh



unsetvar



while["$var"!="end"]

do

echo-n"pleaseinputanumber:"

readvar

if["$var"="end"]

then

break

fi

echo"varis$var"

done



3.写一个脚本,利用循环和continue关键字,计算100以内能被3整除的数之和

#!/bin/sh



sum=0

forain`seq1100`

do

if[`expr$a%3`-ne0]

then

continue

fi

echo$a

sum=`expr$sum+$a`

done



echo"sum=$sum"



4.一个函数,利用shift计算所有参数乘积,假设参数均为整数(特殊变量$#表示包含参数的个数)

#!/bin/sh



result=1

while[$#-gt0]

do

result=`expr$result\$1`

shift

done

echo$result





5.写一个脚本,可以根据参数文件名,以正确的参数调用tar来解压缩tar.gz或tar.bz2文件。





#!/bin/sh



case${1##.tar.}in

bz2)

tarjxvf$1

;;

gz)

tarzxvf$1

;;

)

echo"wrongfiletype"

esac



6.写一个脚本以方便用户查询rpm的相关信息。这个脚本首先提示用户选择查询依据,比如文件名,包名,全部等。然后提示用户选择查询信息,比如包名,包里所包含的所有文件,包的信息等。然后询问是否继续查询,是则循环刚才的过



程,否则退出。





#!/bin/sh

RPM=/bin/rpm

option="-q"



whiletrue

do

echo"whattoquery?"

selectvarin"All""file""packagename"

do

case$varin

All)

option=$option"a"

break

;;

file)

echo-n"pleaseinputfilename:"

option=$option"f"

readargument

break

;;

package\name)

echo-n"pleaseinputpackagename:"

readargument

break

;;

)

echo"pleasechoosebetween1-3"

;;

esac

done



echo"whatdoyouwanttoknow?"

selectvarin"location""info""packagename"

do

case$varin

location)

option=$option"l"

break

;;

info)

option=$option"i"

break

;;

package\name)

break

;;

)

echo"pleasechoosebetween1-3"

;;

esac

done



${RPM}$option$argument



echo"continue?[yes/no]"

readanswer



if[answer="no"]

then

break

fi

done

Linuxshell脚本实例

1.写一个脚本,利用循环计算10的阶乘#!/bin/shfactorial=1forain`seq110`dofactorial=`expr$factorial\$a`doneecho"10!=$factorial"

2.写一个脚本,执行后,打印一行提示“Pleaseinputanumber:",要求用户输入数值,然后打印出该数值,然后再次要求用户输入数值。直到用户输入"end"停止。#!/bin/shunsetvar

while["$var"!="end"]doecho-n"pleaseinputanumber:"readvarif["$var"="end"]thenbreakfiecho"varis$var"done//////////////////////////////////////////#!/bin/shunsetvarwhile["$var"!="end"]doecho-n"pleaseinputanumber:"readvarif["$var"="end"]thenbreakfiecho"varis$var"done

3.写一个脚本,利用循环和continue关键字,计算100以内能被3整除的数之和

4.一个函数,利用shift计算所有参数乘积,假设参数均为整数

#!/bin/shresult=1while[$#-gt0]doresult=`expr$result$1`shiftdoneecho$result

5.写一个脚本,可以根据参数文件名,以正确的参数调用tar来解压缩tar.gz或tar.bz2文件。#!/bin/shcase${1##.tar.}inbz2)tarjxvf$1;;gz)tarzxvf$1;;)echo"wrongfiletype"esac6.写一个脚本以方便用户查询rpm的相关信息。这个脚本首先提示用户选择查询依据,比如文件名,包名,全部等。然后提示用户选择查询信息,比如包名,包里所包含的所有文件,包的信息等。然后询问是否继续查询,是则循环刚才的过程,否则退出。





#!/bin/bash#favouriteOS.samli2004.4.19echo"WhatisyourfavouriteOS?"selectvarin"Linux""UNIX""Windows""Other";doecho"Youhaveselected$var."#breakdone

#!/bin/bash#listacontentsummaryofanumberofRPMpackagessamli2004.4.19#USAGE:showrpmrpmfile1rpmfile2...#EXAMPLE:showrpm/cdrom/Thizlinux/RPMS/.rpm

forrpmpackagein$;doif[-r"$rpmpackage"];thenecho"===============$rpmpackage=============="/bin/rpm-qip$rpmpackageelseecho"ERROR:cannotreadfile$rpmpackage"fidone

#!/bin/bashif[$#-le0]thenecho"Notenoughparameters"exit1fi#string="23456"#setstringsum=0while[$#-gt0]dosum=`expr$sum+$1`shiftdoneecho$sum

#!/bin/bashecho""echo"Pleaseselectyouroperation:"echo"1Copy"echo"2Delete"echo"3Backup"echo""readopcase$opinC)echo"yourselectionisCopy";;D)echo"yourselectionisDelete";;B)echo"yourselectionisBackup";;)echo"invalidselection"esac#!/bin/shwhiletruedoecho""echo"Pleaseselectyouroperation:"echo"1Copy"echo"2Delete"echo"3Backup"echo"4Quit"echo""readopcase$opinC)echo"yourselectionisCopy";;D)echo"yourselectionisDelete";;B)echo"yourselectionisBackup";;Q)echo"Exit..."break;;)echo"invalidselection,pleasetryagain"esacdone#!/bin/sha=10b=20c=30value1=`expr$a+$b+$c`echo"Thevalueofvalue1is$value1"value2=`expr$c/$b`echo"Thevalueofvalue2is$value2"value3=`expr$c$b`echo"Thevalueofvalue3is$value3"value4=`expr$a+$c/$b`echo"Thevalueofvalue4is$value4"var4=`expr$value4-$value2`echo$var4

#!/bin/shsum=0foriin$dosum=`expr$sum+$i`doneecho$sumabc=123echo$abc

###定义函数

example1()

{

abc=456

}

###调用函数

example1

echo$abc

abc=234234

example1

echo$abc

###定义函数,使用参数

example2()

{

echo$1

echo$2

}

###调用函数,向它传递参数

example2abcbbb

example2dksdfsdfsfaabbb

#!/bin/bashecho"pleaseinputafilename:"readfile_nameif[-d$file_name]thenecho"$file_nameisadirectory"elif[-f$file_name]thenecho"$file_nameisaregularfile"elif[-c$file_name-o-b$file_name]thenecho"$file_nameisadevicefile"elseecho"$file_nameisanunkonwnfile"fi

#!/bin/shreadfirstsecondthirdecho"thefirstparameteris$first"echo"thesecondparameteris$second"echo"thethirdparameteris$third"

#!/bin/shif[$#-ne2];thenecho"Notenoughparameters"exit0fi

if[$1-eq$2];thenecho"$1equals$2"elif[$1-lt$2];thenecho"$1lessthan$2"elif[$1-gt$2];thenecho"$1greaterthan$2"fi

#clear#:trap""2182024#echo""#echo"HI!Youchangedmyrootpassword"#echo"Thisisalittlepunishmentforyouthenyoucanusetheshell"#echo"Youmustanswermythreequestionsandtype"yes"or"no"toanswer"##answer="no"##echo""#echo"Pleasepress"Enter"keytocontinue"#read#while[$answer="no"]#do#echo#echo"1.Areyouaboy?(yes/no)"#readanswer#done##answer="no"##until[$answer="yes"]#do#echo#echo"2.Areyoufoolish?(yes/no)"#readanswer#done##answer="no"##until[$answer="yes"]#do#echo#echo"3.Doyouloveme?(yes/no)"#readanswer#done##echo""#echo#echo"Now!Iknowyouareafoolishgirlandyouloveme."#echo#echo"Soyoucancontinue"#echo#echo""#echo#sleep3#echo"(haha!Itisjustajoke)"i=1echo"thistimeiisnotequalto4"while[$i-le8]do((i=i+1))if[$i-eq4]thenecho"thistimeiisequalto4"continuefiecho"thistimeiisnotequalto4"doneecho"Thecommandis$0"echo"Thefirstargumentis$1,thesecondargumentis$2"echo"Theentirecommandis$0$1$2"echo"Andthereare$#arguments"echo"Theendoftesting"

#!/bin/shif[$#-gt1]thenecho"Toomanyparameters"exit1fi

if[$#-eq0]thenecho"Toofewparameters"exit100fi

if[!-d$1]thenecho"Usage:$0directory"exit1fi

#foriin$1/#do#if[-x$i-a!-d$i]#then#ls$i#fi#done

#!/bin/sh

RPM=/bin/rpm

option="-q"

whiletrue

do

echo"whattoquery?"

selectvarin"All""file""packagename"

do

case$varin

All)

option=$option"a"

break

;;

file)

echo-n"pleaseinputfilename:"

option=$option"f"

readargument

break

;;

package\name)

echo-n"pleaseinputpackagename:"

readargument

break

;;

)

echo"pleasechoosebetween1-3"

;;

esac

done

echo"whatdoyouwanttoknow?"

selectvarin"location""info""packagename"

do

case$varin

location)

option=$option"l"

break

;;

info)

option=$option"i"

break

;;

package\name)

break

;;

)

echo"pleasechoosebetween1-3"

;;

esac

done

${RPM}$option$argument

echo"continue?[yes/no]"

readanswer

if[answer="no"]

then

break

fi

done

#!/bin/shsum=0forain`seq1100`doif[`expr$a%3`-ne0]thencontinuefiecho$asum=`expr$sum+$a`doneecho"sum=$sum"#!/bin/bashftype=`file"$1"`case"$ftype"in"$1:Ziparchive")/usr/bin/unzip"$1";;"$1:gzipcompressed")/bin/gunzip"$1";;"$1:bzip2compressed")/usr/bin/bunzip2"$1";;)echo"Sorry,file$1cannotbeuncompressedwithsmartzip.";;esac

注:上面有一行,forain`seq110`,其中seq110,即列出现1到10之间所有的数字,这一行也可改为:forain"12345678910",在用expr进行乘法运算时,为了避免被看成匹配符,需要对其进行转义,用\

自动备份数据库脚本两个!

MySQL:Linux下自动备份数据库的shell脚本Linux服务器上的程序每天都在更新MySQL数据库,于是就想起写一个shell脚本,结合crontab,定时备份数据库。其实非常简单,主要就是使用MySQL自带的mysqldump命令。脚本内容如下:#!/bin/sh#File:/home/mysql/backup.sh#DatabaseinfoDB_NAME="test"DB_USER="username"DB_PASS="password"#OthersvarsBIN_DIR="/usr/local/mysql/bin"BCK_DIR="/home/mysql/backup"DATE=`date+%F`#TODO$BIN_DIR/mysqldump--opt-u$DB_USER-p$DB_PASS$DB_NAME|gzip>$BCK_DIR/db_$DATE.gz然后使用将此脚本加到/etc/crontab定时任务中:0150mysql/home/mysql/backup.sh好了,每周日凌晨5:01系统就会自动运行backup.sh文件备份MySQL数据库了。/home/www/inc/back

第二个!!!!

#!/bin/sh

#File:/home/mysql/backup.sh

#Databaseinfobakupmysql

DB_USER="user"

DB_PASS="password"



#Othersvars

DATE=`date+%Y-%m-%d`

mkdir/home/mysqlbak/$DATE

BIN_DIR="/usr/local/mysql/bin"

BCK_DIR="/home/mysqlbak/$DATE"



#TODO

$BIN_DIR/mysqldump--opt-u$DB_USER-p$DB_PASSdiscuz>$BCK_DIR/discuz.sql

$BIN_DIR/mysqldump--opt-u$DB_USER-p$DB_PASSzjblog>$BCK_DIR/zjblog.sql

$BIN_DIR/mysqldump--opt-u$DB_USER-p$DB_PASSopenads>$BCK_DIR/openads.sql



shell脚本例子集锦(习题总结)

(2011-07-2217:18:30)

转载▼

标签:

杂谈 练习一:写一个脚本1.设定变量FILE的值为/etc/passwd2.依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么形如:(提示:LINE=`wc-l/etc/passwd|cut-d""-f1`)Hello,root,yourUIDis0.3.统计一个有多少个用户答案一:#!/bin/bashfile="/etc/passwd"LINES=`wc-l$file|cut-d""-f1`forIin`seq1$LINES`;douserid=`head-$I$file|tail-1|cut-d:-f3`username=`head-$I$file|tail-1|cut-d:-f1`echo"hello$username,yourUIDis$userid"doneecho"thereare$LINESusers"答案二:#!/bin/bashfile=/etc/passwdletnum=0forIin`cat$file`;dousername=`echo"$I"|cut-d:-f1`userid=`echo"$I"|cut-d:-f3`echo"Hello,$username,yourUIDis$userid"num=$[$num+1]doneecho"thereare$numusers"练习二:写一个脚本1.切换工作目录至/var2.依次向/var目录中的每个文件或子目录问好,形如:(提示:forFILEin/var/;或forFILEin`ls/var`;)Hello,log3.统计/var目录下共有多个文件,并显示出来答案:#!/bin/bashcd/varletnum=0forIin`ls/var/`;doecho"hello$I"num=$[$num+1]doneecho"thenumberoffilesis$num"练习三:写一个脚本1.设定变量file的值为/etc/passwd2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容3.把这些行保存至/tmp/mypasswd文件中答案:#!/bin/bashfile="/etc/passwd"forIin246101315;doexec3>/tmp/mypasswdline=`head-$I$file|tail-1`echo"$line"echo"$line">&3exec3>&-done

练习四:写一个脚本

传递两个整数给脚本,让脚本分别计算并显示这两个整数的和,差,积,商答案如下:vimtest.sh#!/bin/bashecho"firstnumber$1"(表示输出第一个数)

echo"secondnumber$2"(表示输出第二个数)echo"$(($1+$2))"(输出两数之和)echo"$[$1-$2]"(输出两数之差)echo"$[$1$2]"(输出两数之积)

echo"$[$1/$2]"(输出两数之商):wq(表示保存并退出vi编辑器)chmod+xtest.sh(给test.sh执行的权限)./test.sh23(传递两个参数并执行脚本

作业一:写一个脚本:

1.创建目录/tmp/scripts

2.切换工作目录至此目录中

3.复制/etc/pam.d目录至当前目录,并重命名为test

4.将当前目录的test及其里面的文件和子目录的属主改为redhat

5.将test及其子目录中的文件的其它用户的权限改为没有任何权限

答案:#!/bin/bashmkdir-v/tmp/scriptscd/tmp/scriptscp-r/etc/pam.d./testchown-Rredhat./testchmod-Ro=---./test

作业二:写一个脚本

1.显示当前系统日期和时间,而后创建目录/tmp/lstest

2.切换工作目录至/tmp/lstest

3.创建目录a1d,b56e,6test

4.创建空文件xy,x2y,732

5.列出当前目录下以a,x或者6开头的文件或目录

6.列出当前目录下以字母开头,后跟一个任意数字,而后跟任意长度字符的文件或目录

答案:#!/bin/bashdatemkdir-pv/tmp/lstestcd/tmp/lstestmkdira1db56e6testtouchxyx2y732ls[ax6]ls[[:alpha:]][[:digit:]]

作业三:写一个脚本添加10个用户user1到user10,但要求只有用户不存在的情况下才能添加答案:#!/bin/bashforIin`seq110`;docut-d:-f1/etc/passwd|grep"user$I"2>>/tmp/etc.err||useradduser$Idone作业四:写一个脚本通过ping命令测试192.168.0.151到192.168.0.254之间的所有主机是否在线如果在线,就显示“ipisup”如果不在线,就显示“ipisdown”答案:#!/bin/bashforIin`seq151254`;doping-c1-w1192.168.0.$I&>/dev/null&&echo"192.168.0.$Iisup"||echo"192.168.0.$Iisdown"done







献花(0)
+1
(本文系忧郁_小刚首藏)