LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
楼主: KornLee

【shell脚本欣赏区】:[展示你的作品的好去处!欢迎投帖]

[复制链接]
 楼主| 发表于 2003-12-23 22:25:37 | 显示全部楼层

一个文件夹同步脚本

作者:devel
算法:
1.先find /pathname -print >filea #获取两个文件夹里所有文件的全名。
2,比较文件,先删去要同步的文件夹里多余的文件。接着重新获得需要同步的文件夹里所有文件的全名。
3.比较文件,把源文件夹里增加的文件CP到要同步的文件夹中。
这个脚本是同步/share目录里的所有文件,需要备份到/mnt/d/share
  1. #!/bin/bash
  2. mount /dev/hda6 /mnt/d 2>/dev/null ; unalias rm cp
  3. rm /share/c/app/*o /share/c/tmp/*o /share/c/app/*core /share/c/tmp/*core /share/c/app/a.out /share/c/tmp/a.out
  4. find /share -print >/tmp/.share_    #把/share的所有文件的全名保存到/tmp/.share_
  5. find /mnt/d/share -print |sed 's/\/mnt\/d//g' >/tmp/.d_
  6. chmod 700 /tmp/.share_ /tmp/.d_
  7. count=0
  8. for i in $(comm -23 /tmp/.d_ /tmp/.share_) ; do     #比较两个文件里/tmp.d_ 与/tmp./share_的不同。
  9. echo "/mnt/d$i"
  10. rm "/mnt/d$i" ; count=$((count+1))    #删除/mnt/d/share/*里的多余的文件和计数。
  11. done    #for command ;do command ; done的循环到此结束。
  12. echo "del $count file at /mnt/d/share/"
  13. find /mnt/d/share -print |sed 's/\/mnt\/d//g' >/tmp/.d_ ; count=0    #重新获得文件的全名。初始化计数器。
  14. for i in $(comm -23 /tmp/.share_ /tmp/.d_) ; do
  15. echo $i
  16. cp $i "/mnt/d$i" ; count=$((count+1))    #备份/share里新增加的文件到/mnt/d/share,同时计数。
  17. done
  18. echo "already copied $count file from /share to /mnt/d/share " ;sync
  19. umount /mnt/d 2>/dev/null
  20. echo done
复制代码
 楼主| 发表于 2003-12-26 23:00:44 | 显示全部楼层

slackware添加用户adduser脚本欣赏

转贴:北南南北
作者:Stuart Winter <stuart@polplex.co.uk>
这是slackware中的添加用户的一个脚本,感觉写的很好,就帖了上来。想和弟兄们一起学习SHELL。
  1. #!/bin/sh
  2. ##########################################################################
  3. # Program: /usr/sbin/adduser
  4. # Purpose: Interactive front end to /usr/sbin/useradd for Slackware Linux
  5. # Author:  Stuart Winter <stuart@polplex.co.uk>
  6. #          based on the original Slackware adduser by Hrvoje Dogan
  7. #          with modifications by Patrick Volkerding
  8. # Version: 1.05
  9. ##########################################################################
  10. # History #
  11. ###########
  12. # v1.05 - 04/01/03
  13. #       * Advise & prevent users from creating logins with '.' characters
  14. #         in the user name.
  15. #       * Made pending account creation info look neater
  16. # v1.04 - 09/06/02
  17. #       * Catered for shadow-4.0.3's 'useradd' binary that no longer
  18. #         will let you create a user that has any uppercase chars in it
  19. #         This was reported on the userlocal.org forums
  20. #         by 'xcp' - thanks. <sw,pjv>
  21. # v1.03 - 20/05/02
  22. #       * Support 'broken' (null lines in) /etc/passwd and
  23. #         /etc/group files <sw>
  24. #       * For recycling UIDs (default still 'off'), we now look in
  25. #         /etc/login.defs for the UID_MIN value and use it
  26. #         If not found then default to 1000 <sw>
  27. # v1.02 - 10/04/02
  28. #       * Fix user-specified UID bug. <pjv>
  29. # v1.01 - 23/03/02
  30. #       * Match Slackware indenting style, simplify. <pjv>
  31. # v1.00 - 22/03/02
  32. #       * Created
  33. #######################################################################
  34. # Syntax: adduser [<new_user_name>]
  35. #######################################################################
  36.                                                                                 
  37. # Path to files
  38. pfile=/etc/passwd
  39. gfile=/etc/group
  40. sfile=/etc/shells
  41.                                                                                 
  42. # Paths to binaries
  43. useradd=/usr/sbin/useradd
  44. chfn=/usr/bin/chfn
  45. passwd=/usr/bin/passwd
  46. chmod=/bin/chmod
  47.                                                                                 
  48. # Defaults
  49. defhome=/home
  50. defshell=/bin/bash
  51. defchmod=711 # home dir permissions - may be preferable to use 701, however.
  52.                                                                                 
  53. # Determine what the minimum UID is (for UID recycling)
  54. # (we ignore it if it's not at the beginning of the line (i.e. commented out wit
  55. h #))
  56. export recycleUIDMIN="$(grep ^UID_MIN /etc/login.defs | awk {'print $2'} 2>/dev/
  57. null)"
  58. # If we couldn't find it, set it to the default of 1000
  59. if [ -z "$recycleUIDMIN" ]; then
  60.    export recycleUIDMIN=1000  # this is the default from /etc/login.defs
  61. fi
  62.                                                                                 
  63.                                                                                 
  64. # This setting enables the 'recycling' of older unused UIDs.
  65. # When you userdel a user, it removes it from passwd and shadow but it will
  66. # never get used again unless you specify it expliticly -- useradd just
  67. # (appears to) looks at the last line in passwd and increments the uid
  68. # I like the idea of recycling uids but you may have very good reasons not to
  69. # (old forgotten confidential files still on the system could then be owned by
  70. # this new user).  We'll set this to no because this is what the original
  71. # adduser shell script did and it's what users expect.
  72. recycleuids=no
  73.                                                                                 
  74. # Function to read keyboard input.
  75. # bash1 is broken (even ash will take read -ep!), so we work around
  76. # it (even though bash1 is no longer supported on Slackware).
  77. function get_input() {
  78.   local output
  79.   if [ "`echo $BASH_VERSION | cut -b1`" = "1" ]; then
  80.     echo -n "${1} " >&2 ; # fudge for use with bash v1
  81.     read output
  82.   else # this should work with any other /bin/sh
  83.     read -ep "${1} " output
  84.   fi
  85.   echo $output
  86. }
  87.                                                                                 
  88. # Function to display the account info
  89. function display () {
  90.   local goose
  91.   goose="$(echo $2 | cut -d ' ' -f 2-)"  # lop off the prefixed argument useradd
  92. needs
  93.   echo -n "$1 "
  94.   # If it's null then display the 'other' information
  95.   if [ -z "$goose" -a ! -z "$3" ]; then
  96.     echo "$3"
  97.   else
  98.     echo "$goose"
  99.   fi
  100. }
  101.                                                                                 
  102. # Function to check whether groups exist in the /etc/group file
  103. function check_group () {
  104.   local got_error group
  105.   if [ ! -z "$@" ]; then
  106.   for group in $@ ; do
  107.     local uid_not_named="" uid_not_num=""
  108.     grep -v "$^" $gfile | awk -F: '{print $1}' | grep "^${group}$" >/dev/null 2>
  109. &1 || uid_not_named=yes
  110.     grep -v "$^" $gfile | awk -F: '{print $3}' | grep "^${group}$" >/dev/null 2>
  111. &1 || uid_not_num=yes
  112.     if [ ! -z "$uid_not_named" -a ! -z "$uid_not_num" ]; then
  113.       echo "- Group '$group' does not exist"
  114.       got_error=yes
  115.     fi
  116.   done
  117.   fi
  118.   # Return exit code of 1 if at least one of the groups didn't exist
  119.   if [ ! -z "$got_error" ]; then
  120.     return 1
  121.   fi
  122. }
  123.                                                                                 
  124. #: Read the login name for the new user :#
  125. #
  126. # Remember that most Mail Transfer Agents are case independant, so having
  127. # 'uSer' and 'user' may cause confusion/things to break.  Because of this,
  128. # useradd from shadow-4.0.3 no longer accepts usernames containing uppercase,
  129. # and we must reject them, too.
  130.                                                                                 
  131. # Set the login variable to the command line param
  132. echo
  133. LOGIN="$1"
  134. needinput=yes
  135. while [ ! -z $needinput ]; do
  136.   if [ -z "$LOGIN" ]; then
  137.     while [ -z "$LOGIN" ]; do LOGIN="$(get_input "Login name for new user []:")"
  138. ; done
  139.   fi
  140.   grep "^${LOGIN}:" $pfile >/dev/null 2>&1  # ensure it's not already used
  141.   if [ $? -eq 0 ]; then
  142.     echo "- User '$LOGIN' already exists; please choose another"
  143.     unset LOGIN
  144.   elif [ ! "$LOGIN" = "`echo $LOGIN | tr A-Z a-z`" ]; then # useradd does not al
  145. low uppercase
  146.     echo "- User '$LOGIN' contains illegal characters (uppercase); please choose
  147. another"
  148.     unset LOGIN
  149.   elif [ ! -z "$( echo $LOGIN | grep '\.' )" ]; then
  150.     echo "- User '$LOGIN' contains illegal characters (period/dot); please choos
  151. e another"
  152.     unset LOGIN
  153.   else
  154.     unset needinput
  155.   fi
  156. done
  157.                                                                                 
  158. # Display the user name passed from the shell if it hasn't changed
  159. if [ "$1" = "$LOGIN" ]; then
  160.   echo "Login name for new user: $LOGIN"
  161. fi
  162.                                                                                 
  163. #: Get the UID for the user & ensure it's not already in use :#
  164. #
  165. # Whilst we _can_ allow users with identical UIDs, it's not a 'good thing' becau
  166. se
  167. # when you change password for the uid, it finds the first match in /etc/passwd
  168. # which isn't necessarily the correct user
  169. #
  170. echo
  171. needinput=yes
  172. while [ ! -z "$needinput" ]; do
  173.   _UID="$(get_input "User ID ('UID') [ defaults to next available ]:")"
  174.   grep -v "^$" $pfile | awk -F: '{print $3}' | grep "^${_UID}$" >/dev/null 2>&1
  175.   if [ $? -eq 0 ]; then
  176.     echo "- That UID is already in use; please choose another"
  177.   elif [ ! -z "$(echo $_UID | egrep [A-Za-z])" ]; then
  178.     echo "- UIDs are numerics only"
  179.   else
  180.     unset needinput
  181.   fi
  182. done
  183. # If we were given a UID, then syntax up the variable to pass to useradd
  184. if [ ! -z "$_UID" ]; then
  185.   U_ID="-u ${_UID}"
  186. else
  187.   # Will we be recycling UIDs?
  188.   if [ "$recycleuids" = "yes" ]; then
  189.     U_ID="-u $(awk -F: '{uid[$3]=1} END { for (i=ENVIRON["recycleUIDMIN"];i in u
  190. id;i++);print i}' $pfile)"
  191.   fi
  192. fi
  193.                                                                                 
  194. #: Get the initial group for the user & ensure it exists :#
  195. #
  196. # We check /etc/group for both the text version and the group ID number
  197. echo
  198. needinput=yes
  199. while [ ! -z "$needinput" ]; do
  200.   GID="$(get_input "Initial group [ users ]:")"
  201.   check_group "$GID"
  202.   if [ $? -gt 0 ]; then
  203.     echo "- Please choose another"
  204.   else
  205.     unset needinput
  206.   fi
  207. done
  208. # Syntax the variable ready for useradd
  209. if [ -z "$GID" ]; then
  210.   GID="-g users"
  211. else
  212.   GID="-g ${GID}"
  213. fi
  214.                                                                                 
  215. #: Get additional groups for the user :#
  216. #
  217. echo
  218. needinput=yes
  219. while [ ! -z "$needinput" ]; do
  220.   AGID="$(get_input "Additional groups (comma separated) []:")"
  221.   AGID="$(echo "$AGID" | tr -d ' ' | tr , ' ')" ; # fix up for parsing
  222.   if [ ! -z "$AGID" ]; then
  223.     check_group "$AGID"  # check all groups at once (treated as N # of params)
  224.     if [ $? -gt 0 ]; then
  225.       echo "- Please re-enter the group(s)"
  226.     else
  227.       unset needinput # we found all groups specified
  228.       AGID="-G $(echo "$AGID" | tr ' ' ,)"
  229.     fi
  230.   else
  231.     unset needinput   # we don't *have* to have additional groups
  232.   fi
  233. done
  234.                                                                                 
  235. #: Get the new user's home dir :#
  236. #
  237. echo
  238. needinput=yes
  239. while [ ! -z "$needinput" ]; do
  240.   HME="$(get_input "Home directory [ ${defhome}/${LOGIN} ]")"
  241.   if [ -z "$HME" ]; then
  242.     HME="${defhome}/${LOGIN}"
  243.   fi
  244.   # Warn the user if the home dir already exists
  245.   if [ -d "$HME" ]; then
  246.     echo "- Warning: '$HME' already exists !"
  247.     getyn="$(get_input "  Do you wish to change the home directory path? (Y/n) "
  248. )"
  249.     if [ "$(echo $getyn | grep -i "n")" ]; then
  250.       unset needinput
  251.     fi
  252.   else
  253.     unset needinput
  254.   fi
  255. done
  256. HME="-d ${HME}"
  257.                                                                                 
  258. #: Get the new user's shell :#
  259. echo
  260. needinput=yes
  261. while [ ! -z "$needinput" ]; do
  262.   unset got_error
  263.   SHL="$(get_input "Shell [ ${defshell} ]")"
  264.   if [ -z "$SHL" ]; then
  265.     SHL="${defshell}"
  266.   fi
  267.   # Warn the user if the shell doesn't exist in /etc/shells or as a file
  268.   if [ -z "$(grep "^${SHL}$" $sfile)" ]; then
  269.     echo "- Warning: ${SHL} is not in ${sfile} (potential problem using FTP)"
  270.     got_error=yes
  271.   fi
  272.   if [ ! -f "$SHL" ]; then
  273.     echo "- Warning: ${SHL} does not exist as a file"
  274.     got_error=yes
  275.   fi
  276.   if [ ! -z "$got_error" ]; then
  277.     getyn="$(get_input "  Do you wish to change the shell? (Y/n) ")"
  278.     if [ "$(echo $getyn | grep -i "n")" ]; then
  279.       unset needinput
  280.     fi
  281.   else
  282.     unset needinput
  283.   fi
  284. done
  285. SHL="-s ${SHL}"
  286.                                                                                 
  287. #: Get the expiry date :#
  288. echo
  289. needinput=yes
  290. while [ ! -z "$needinput" ]; do
  291.   EXP="$(get_input "Expiry date (YYYY-MM-DD) []:")"
  292.   if [ ! -z "$EXP" ]; then
  293.     # Check to see whether the expiry date is in the valid format
  294.     if [ -z "$(echo "$EXP" | grep "^[[:digit:]]\{4\}[-]\?[[:digit:]]\{2\}[-]\?[[
  295. :digit:]]\{2\}$")" ]; then
  296.       echo "- That is not a valid expiration date"
  297.     else
  298.       unset needinput
  299.       EXP="-e ${EXP}"
  300.     fi
  301.   else
  302.     unset needinput
  303.   fi
  304. done
  305.                                                                                 
  306. # Display the info about the new impending account
  307. echo
  308. echo "New account will be created as follows:"
  309. echo
  310. echo "---------------------------------------"
  311. display "Login name.......: " "$LOGIN"
  312. display "UID..............: " "$_UID" "[ Next available ]"
  313. display "Initial group....: " "$GID"
  314. display "Additional groups: " "$AGID" "[ None ]"
  315. display "Home directory...: " "$HME"
  316. display "Shell............: " "$SHL"
  317. display "Expiry date......: " "$EXP" "[ Never ]"
  318. echo
  319.                                                                                 
  320. echo "This is it... if you want to bail out, hit Control-C.  Otherwise, press"
  321. echo "ENTER to go ahead and make the account."
  322. read junk
  323.                                                                                 
  324. echo
  325. echo "Creating new account..."
  326. echo
  327. echo
  328.                                                                                 
  329. # Add the account to the system
  330. CMD="$useradd "$HME" -m "$EXP" "$U_ID" "$GID" "$AGID" "$SHL" "$LOGIN""
  331. $CMD
  332.                                                                                 
  333. if [ $? -gt 0 ]; then
  334.   echo "- Error running useradd command -- account not created!"
  335.   echo "(cmd: $CMD)"
  336.   exit 1
  337. fi
  338.                                                                                 
  339. # Set the finger information
  340. $chfn "$LOGIN"
  341. if [ $? -gt 0 ]; then
  342.   echo "- Warning: an error occurred while setting finger information"
  343. fi
  344.                                                                                 
  345. # Set a password
  346. $passwd "$LOGIN"
  347. if [ $? -gt 0 ]; then
  348.   echo "* WARNING: An error occured while setting the password for"
  349.   echo "           this account.  Please manually investigate this *"
  350.   exit 1
  351. fi
  352.                                                                                 
  353. # If it was created (it should have been!), set the permissions for that user's
  354. dir
  355. HME="$(echo "$HME" | awk '{print $2}')"  # We have to remove the -g prefix
  356. if [ -d "$HME" ]; then
  357.   $chmod $defchmod "$HME"
  358. fi
  359.                                                                                 
  360. echo
  361. echo
  362. echo "Account setup complete."
  363. exit 0
复制代码
 楼主| 发表于 2003-12-27 18:50:22 | 显示全部楼层

终止进程的脚本

来自: <<Red Hat Linux 8 宝典>>
  1. #!/bin/bash
  2. #
  3. for i in `echo $*`;do
  4.         for j in 15 2 1 9;do
  5.                 kill -$j $i && sleep 1
  6.         done
  7. done
  8. exit 0
复制代码
 楼主| 发表于 2003-12-27 22:30:42 | 显示全部楼层

查询用户登录总时间脚本

作者:javalee
  1. [/home/javalee/myshell]cat logtime
  2. #!/bin/ksh
  3. #这是一个查询用户登录系统总时间的脚本
  4. #
  5. #脚本开始
  6. (($#>0))&&{ echo "Usage:$(basename $0) [Enter]";exit 1; }
  7. read name?"input username:"
  8. if ! grep -q "\<$name\>" /etc/passwd;then
  9.         echo "No Found User:$1!"
  10.         exit
  11. fi
  12. #定义_do函数
  13. function _do {
  14. last $name|sed -n '2,$p'|sed 's/ \(([0-2][0-2]:[0-5][0-9])\)/#\1/g;s/(//g;s/)//g'|cut -f2 -d"#"|\
  15. awk -F: '{sum1+=$1;sum2+=$2};END{print sum1,sum2}'
  16. }
  17. #
  18. #生成小时和分钟的变量
  19. HH=$(_do|cut -f1 -d" ")
  20. MM=$(_do|cut -f2 -d" ")
  21. #
  22. #
  23. #取出小时和分钟
  24. #判断分钟域,如果$MM大于60,那么换算并显示结果
  25. if [[ $MM -gt 60 ]]; then
  26.         ((m1=$MM/60))
  27.         ((m2=$MM%60))
  28.         echo "用户$name登录系统总时间:$((m1+$HH))小时$m2分"
  29. else
  30.         echo "用户$name登录系统总时间:$HH小时$MM分"
  31. fi
  32. #
  33. #
  34. #脚本结束
复制代码
 楼主| 发表于 2003-12-29 03:42:26 | 显示全部楼层

拨号计时脚本

作者:javalee
  1. [/home/javalee]cat ~/myshell/ppp
  2. #!/bin/ksh
  3. #本脚本用于统计每次拨号上网所耗时间,用帽拨号的也许用得着.
  4. #放在/etc/rc.d/rc.local中,/xxx/xxx/ppp&,脚本要用绝对路
  5. #径!另外将
  6. #数据文件改成666即可
  7. #
  8. #脚本开始
  9. #建立函数_ps,便于重复调用.
  10. function _ps { ps -e|grep pppd; }
  11. line=$(cat /home/javalee/.log.txt|wc -l)
  12. #进入主循环.
  13. #
  14. while true;do
  15. #辅循环,如果pppd进程存在,则跳过此循环,否则等待.
  16.         until _ps>/dev/null 2>&1;do
  17.                 sleep 1
  18.         done
  19. #pppd进程存在,找出进程启动时间.并将此时间添加至文件/home/javalee/.log.txt
  20.         echo "上线时间:$(date +%T)" >>/home/javalee/.log.txt
  21.         uptime=$(date +%s)
  22. #辅循环,pppd进程存在,则等待,否则,将当前时间添加至文件/home/javalee/.log.txt
  23.         while _ps >/dev/null 2>&1;do
  24.                 sleep 1
  25.         done
  26.         echo "下线时间:$(date +%T)" >>/home/javalee/.log.txt
  27.         downtime=$(date +%s)
  28. #pppd进程已经不复存在,统计时间.并将结果添加至文件/home/javalee/.log.txt
  29. ((result_time=$downtime-$uptime))
  30. H=$(($result_time/3600))
  31. M=$(($result_time%3600))
  32. if [[ $M -ge 59 ]];then
  33.         M1=$(($M/60));M2=$(($M%60))
  34.         echo "第$line次上网在$(date +%m月%d日):用时:$H小时$M1分$M2秒">>/home/javalee/.log.txt
  35. else
  36.         echo "第$line次上网在$(date +%m月%d日):用时:$H时$M分0秒">>/home/javalee/.log.txt
  37. fi
  38. ((line+=1))
  39. #继续主循环.
  40.         continue
  41. done
复制代码
写了这个脚本,每次我就知道我每次上网的时间,用时多少啦,
 楼主| 发表于 2004-1-3 01:36:37 | 显示全部楼层

一个利用suspend控制终端的脚本

作者:javalee
  1. #!/bin/ksh
  2. #这是一个能让所有字符终端挂起/恢复的脚本
  3. #这是一个suspend这个shell内置命令的应用例子
  4. #适用字符模式,root身份
  5. #作者:javalee
  6. #控制终端有很多方式,欢迎指教
  7. #
  8. #脚本开始
  9. ###找出自己的终端名
  10. owntty=$(tty)
  11. ###找出所有登录终端PID
  12. pid=$(ps -e|awk '/tty[0-9]/&&/[ba|k]sh/'|grep -v "$owntty"|awk '{print $1}')
  13. ###必要信息提示
  14. (($#!=1))&&{ echo "Usage:$(basename $0) [k|r]\nk:send HUP \
  15. signal to all tty\nr:send CONT signal to all tty";exit 1; }
  16. ###检查命令行参数
  17. case $1 in
  18.         k)      echo "all tty STOP..."
  19.         for i in $pid;do
  20. ###挂起登录终端正在执行的shell,不要把自己也"挂"啦 :)
  21.                 (suspend $i)&&kill -18 $$ >/dev/null 2>&1
  22.         done
  23.         ;;
  24.         r)      echo "all tty RESTART..."
  25.         for i in $pid;do
  26. ###恢复
  27.                 kill -18 $i >/dev/null 2>&1
  28.         done
  29.         ;;
  30. esac
  31. #
  32. #
  33. #脚本结束
复制代码
发表于 2004-1-18 22:20:26 | 显示全部楼层
找文件中某个KEY的脚本,版本2

  1. #!/bin/bash
  2. #A bash script to find a keyword.    Name: findkey Version : 2.0  Author: devel
  3. echo -n " ";pwd;date#空一格,显示当前路径和日期
  4. while true;do#循环
  5.   echo "Input a directory or file :   # will exit if press e|E !"
  6.   echo -n " ";read dir ; until [ $dir ] ;do read dir ;done#空出一格,从标准输入读取字符知道不为空
  7.   case $dir in
  8.     e|E)  echo done ;exit 0
  9.           ;;
  10.     *)
  11.           if [ -e $dir ];then#-e是检查文件是否存在
  12.               echo "Input keyword:              # will exit if press e|E !
  13.                                #  Will reread a directory or file if you press r|R  !"
  14.               echo -n " "; read "key" ; until [ $key ] ;do read key ;done
  15.               case $key in
  16.                      e|E)   echo done ;exit 0                         ;;
  17.                      r|R)   continue                                  ;;#要求重新从标准输入读取路径
  18.                        *)   grep -R "$key" $dir|cat -n  2>/dev/null|less ;;#找出文件并排序
  19.               esac
  20.           else echo "The directory or file did not exist  "
  21.           fi
  22.           ;;
  23.   esac
  24. done
复制代码


非常好用,我很喜欢它!!
发表于 2004-1-30 14:10:52 | 显示全部楼层
介绍一个脚本
作者:icyblue

标题: 初学bash(icyblue)

  

今天要分割一个文件, 以前在windows下有个filesplit的小东东

linux也有个split可以做, 可惜知道得晚了一步

想想用dd好像也容易实现, 就一边info bash自力更生了一个split

  

--------------begin-----------------

  

#!/bin/bash

  

if [ $# -ne 2 ]; then

        echo    'Usage: split file size(in bytes)'

        exit

fi

  

file=$1

size=$2

  

if [ ! -f $file ]; then

        echo "$file doesn't exist"

        exit

fi

  

#TODO: test if $size is a valid integer

  

filesize=`/bin/ls -l $file | awk '{print $5}'`

echo filesize: $filesize

  

let pieces=$filesize/$size

let remain=$filesize-$pieces*$size

if [  $remain -gt 0 ]; then

        let pieces=$pieces+1

fi

echo pieces: $pieces

  

i=0

while [ $i -lt $pieces ];

do

        echo split: $file.$i:

        dd if=$file of=$file.$i bs=$size count=1 skip=$i

        let i=$i+1

done

  

echo "#!/bin/bash" > merge

  

echo "i=0" >> merge

echo "while [ \$i -lt $pieces ];" >> merge

echo "do" >> merge

echo "  echo merge: $file.\$i" >> merge

echo "  if [ ! -f $file.\$i ]; then" >> merge

echo "          echo merge: $file.\$i missed" >> merge

echo "          rm -f $file.merged" >> merge

echo "          exit" >> merge

echo "  fi" >> merge

echo "  dd if=$file.\$i of=$file.merged bs=$size count=1 seek=\$i" >> merge

echo "  let i=\$i+1" >> merge

echo "done" >> merge

chmod u+x merge

  

-----------end---------------
 楼主| 发表于 2004-2-17 18:48:32 | 显示全部楼层

一个自动分区脚本

感谢作者:home_king兄
part_it:
[php]

#!/bin/sh
# Create partitions(logical for slave hard disk automatically.
# WARNNING!!!
# Your hard disk must be empty initially,
# OTHERWISE this script does not process!
#
# Written by home_king <home_king@163.com>
#
                                                                                
# Check parted
if [ "$(whereis parted | awk '{print $2}')" = "" ]; then
        echo "arted is not installed!"
        exit 1
fi
# Create partition
if [ -n "$1" ]; then
        bdev=$1
        if [ -n "$(parted -s $bdev print |grep ^1)" ]; then
                echo 'Your hard disk must be not partitioned yet!!!'
                exit 1
        fi
        tmpvar=$(parted -s $1 print |grep "Disk geometry" |awk '{print $5}')
        edge=${tmpvar##*-}
        iedge=${edge%%.*}
        # Create refer to config_file
        if [ -n "$2" ] && [ -f $2 ]; then
                config_file=$2
                rm -f tmpfile
                cat $config_file |grep ^[1-9] > tmpfile
                startM=0
                lastflag=0
                while read size parttype fs; do
                        if [ $((size-0)) -eq 0 ] || [ $size -le 0 ]; then
                                echo 'Invalid "size" format!!!'
                                exit 1
                        fi
                        case $parttype in
                                l) parttype="logical";;
                                p) parttype="primary";;
                                *) echo 'Invalid part type!!![logical|primary]'
                                   exit 1;;
                        esac
                        case $fs in
                                ext2) fs="ext2";;
                                *) echo 'Invalid filesystem!!![Now just support ext2]'
                                   exit 1;;
                        esac
                        endM=$(($size+$startM))
                        if [ $endM -gt $iedge ]; then
                                lastflag=1
                                endM=$edge
                        fi
                        parted -s $bdev mkpartfs $parttype $fs $startM $endM
                        [ $lastflag -eq 1 ] && exit 0
                        startM=$endM
                done < tmpfile
        # Auto mode
        else
                flag=""
                until [ "$flag" = "y" ] || [ "$flag" = "n" ]; do
                        read -p 'WRNNING!!!NO CONFIG!!!Auto mode?[y/n]' flag
                done
                [ "$flag" = "n" ] && echo "exit" && exit 1
                avrsize=$(($iedge/4))
                startM=0
                i=1
                until [ $i -gt 3 ]; do
                        endM=$(($avrsize*$i))
                        parted -s /dev/hda mkpartfs logical ext2 $startM $endM
                        startM=$endM
                        i=$((i+1))
                done
                parted -s /dev/hda mkpartfs logical ext2 $startM $edge
                echo "All done!!!"
                echo
                parted -s /dev/hda print
        fi
else
        echo "You must input device to process!"
        exit 1
fi[/php]
用法是
chmod +x part_it
./part_it /dev/hdX config-file
其中/dev/hdX是你的从盘,如X是b;
config-file是分区配置文件,格式如下

#size   parttype        fs
6000    l       ext2
2000    l       ext2
8000    l       ext2

第一列是分区大小,第二列是分区类型(logical,缩写l,代表逻辑分区),第三列是文件系统,.三列用TAB键分开!!!
由于不知道你的具体要求是什么,只好仅仅支持逻辑分区以及ext2,兄弟最好在这个基础上自己修改一下脚本.
另外,脚本会自动判别你是否已分区,配置文件中总的size是否超出硬盘容量等等.
仅提供参考,后果自负!!!
 楼主| 发表于 2004-2-17 18:52:36 | 显示全部楼层

一个删除无效链接的脚本

感谢作者:home_king兄
说明
1.专家模式(删除前免提示),且进入专家模式前作出提示
2.仅作用于一层目录的功能选项
3.该脚本利用find的目录递归功能删除系统上无效(目标文件不存在)的软链接
[php]
#!/bin/sh
# When lpath is /, it can delete all null links existing in your system INTERACTIVELY!!!
#
# Written by home_king<home_king@163.com>
#
                                                                                
prompthelp()
{
        echo ========================================
        echo 'Delete symbolic links with null target.'
        echo 'usage:dellink [-e] [-o] [PATH]'
        echo '  -f:EXPERT mode,no prompt.WARNNING!!!'
        echo '  -c:Just apply to current directory.'
        echo '  -hrint this help.'
        echo '  Without PATH, we set it ".".'
        echo ========================================
}
delflag=""
promptdel()
{
        read -p 'WARNNING!!!Without PROMPT!!!Continue?[y/n]' delflag
        case $delflag in
                y ) return 0;;
                n ) exit 1;;
                * ) promptdel
        esac
}
while getopts ":fch" opt; do
        case $opt in
                f  ) INTERACTIVE="f"
                     promptdel;;
                c  ) DEPTH="maxdepth 1";;
                h  ) prompthelp
                     exit 0;;
                \? ) echo "Invalid Option!"
                     prompthelp
                     exit 1
        esac
done
shift $(($OPTIND - 1))
lpath=$1
[ $# -gt 1 ] && prompthelp && exit 1
if [ -d $1 ]; then
        linklist=$(find $1 -${DEPTH:-"depth"} -type l |xargs)
        for i in $linklist; do
                [ ! -f $i ] && rm -${INTERACTIVE:-"i"} $i
        done
else
        echo "ATH is not a directory!"
        prompthelp
fi[/php]
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表