1. 程式人生 > >Linux常用shell腳本

Linux常用shell腳本

format echo 用戶名 util iss bin ecif argument pla

在運維中,尤其是linux運維,都知道腳本的重要性,腳本會讓我們的 運維事半功倍,所以學會寫腳本是我們每個linux運維必須學會的一門功課,如何學好腳本,最關鍵的是就是大量的練習 和實踐。

1.用Shell編程,判斷一文件是不是字符設備文件,如果是將其拷貝到 /dev 目錄下。


參考程序:

C代碼 技術分享
  1. #!/bin/sh
  2. FILENAME=
  3. echo “Input file name:”
  4. read FILENAME
  5. if [ -c "$FILENAME" ]
  6. then
  7. cp $FILENAME /dev
  8. fi

2.設計一個shell程序,添加一個新組為class1,然後添加屬於這個組的30個用戶,用戶名的形式為stdxx,其中xx從01到30。


參考答案:

C代碼 技術分享
  1. #!/bin/sh
  2. i=1
  3. groupadd class1
  4. while [ $i -le 30 ]
  5. do
  6. if [ $i -le 9 ] ;then
  7. USERNAME=stu0${i}
  8. else
  9. USERNAME=stu${i}
  10. fi
  11. useradd $USERNAME
  12. mkdir /home/$USERNAME
  13. chown -R $USERNAME /home/$USERNAME
  14. chgrp -R class1 /home/$USERNAME
  15. i=$(($i+1))
  16. done


3.編寫shell程序,實現自動刪除50個賬號的功能。賬號名為stud1至stud50。

參考程序:

C代碼 技術分享
  1. #!/bin/sh
  2. i=1
  3. while [ $i -le 50 ]
  4. do
  5. userdel -r stud${i}
  6. i=$(($i+1 ))
  7. done


4.某系統管理員需每天做一定的重復工作,請按照下列要求,編制一個解決方案:
(1)在下午4 :50刪除/abc目錄下的全部子目錄和全部文件;
(2)從早8:00~下午6:00每小時讀取/xyz目錄下x1文件中每行第一個域的全部數據加入到/backup目錄下的bak01.txt文件內;
(3)每逢星期一下午5:50將/data目錄下的所有目錄和文件歸檔並壓縮為文件:backup.tar.gz;
(4)在下午5:55將IDE接口的CD-ROM卸載(假設:CD-ROM的設備名為hdc);
(5)在早晨8:00前開機後啟動。


參考答案:
解決方案:
(1)用vi創建編輯一個名為prgx的crontab文件;
(2)prgx文件的內容:

C代碼 技術分享
  1. 50 16 * * * rm -r /abc/*
  2. 0 8-18/1 * * * cut -f1 /xyz/x1 >;>; /backup/bak01.txt
  3. 50 17 * * * tar zcvf backup.tar.gz /data
  4. 55 17 * * * umount /dev/hdc


(3)由超級用戶登錄,用crontab執行 prgx文件中的內容:
[email protected]:#crontab prgx;在每日早晨8:00之前開機後即可自動啟動crontab。


5.設計一個shell程序,在每月第一天備份並壓縮/etc目錄的所有內容,存放在/root/bak目錄裏,且文件名為如下形式yymmdd_etc,yy為年,mm為月,dd為日。Shell程序fileback存放在/usr/bin目錄下。

參考答案:
(1)編寫shell程序fileback:

C代碼 技術分享
  1. #!/bin/sh
  2. DIRNAME=`ls /root | grep bak`
  3. if [ -z "$DIRNAME" ] ; then
  4. mkdir /root/bak
  5. cd /root/bak
  6. fi
  7. YY=`date +%y`
  8. MM=`date +%m`
  9. DD=`date +%d`
  10. BACKETC=$YY$MM$DD_etc.tar.gz
  11. tar zcvf $BACKETC /etc
  12. echo “fileback finished!”


(2)編寫任務定時器:

C代碼 技術分享
  1. echo “0 0 1 * * /bin/sh /usr/bin/fileback” >; /root/etcbakcron
  2. crontab /root/etcbakcron
  3. 或使用crontab -e 命令添加定時任務:
  4. 0 1 * * * /bin/sh /usr/bin/fileback


6.有一普通用戶想在每周日淩晨零點零分定期備份/user/backup到/tmp目錄下,該用戶應如何做?

參考答案:

(1)第一種方法:

C代碼 技術分享
  1. 用戶應使用crontab –e 命令創建crontab文件。格式如下:
  2. 0 0 * * sun cp –r /user/backup /tmp


(2)第二種方法:
用戶先在自己目錄下新建文件file,文件內容如下:

C代碼 技術分享
  1. 0 * * sun cp –r /user/backup /tmp

然後執行 crontab file 使生效。


7.設計一個Shell程序,在/userdata目錄下建立50個目錄,即user1~user50,並設置每個目錄的權限,其中其他用戶的權限為:讀;文件所有者的權限為:讀、寫、執行;文件所有者所在組的權限為:讀、執行。

參考答案: 建立程序 Pro16如下:

C代碼 技術分享
  1. #!/bin/sh
  2. i=1
  3. while [ i -le 50 ]
  4. do
  5. if [ -d /userdata ];then
  6. mkdir -p /userdata/user$i
  7. chmod 754 /userdata/user$i
  8. echo “user$i”
  9. let “i = i + 1″ (或i=$(($i+1))
  10. else
  11. mkdir /userdata
  12. mkdir -p /userdata/user$i
  13. chmod 754 /userdata/user$i
  14. echo “user$i”
  15. let “i = i + 1″ (或i=$(($i+1))
  16. fi
  17. done

8、MySQL備份實例,自動備份mysql,並刪除30天前的備份文件

C代碼 技術分享
  1. #!/bin/sh
  2. #auto backup mysql
  3. #wugk 2012-07-14
  4. #PATH DEFINE
  5. BAKDIR=/data/backup/mysql/`date +%Y-%m-%d`
  6. MYSQLDB=www
  7. MYSQLPW=backup
  8. MYSQLUSR=backup
  9. if[ $UID -ne 0 ];then
  10. echo This script must use administrator or root user ,please exit!
  11. sleep 2
  12. exit 0
  13. fi
  14. if[ ! -d $BAKDIR ];then
  15. mkdir -p $BAKDIR
  16. else
  17. echo This is $BAKDIR exists ,please exit ….
  18. sleep 2
  19. exit
  20. fi
  21. ###mysqldump backup mysql
  22. /usr/bin/mysqldump -u$MYSQLUSR -p$MYSQLPW -d $MYSQLDB >/data/backup/mysql/`date +%Y-%m-%d`/www_db.sql
  23. cd $BAKDIR ; tar -czf www_mysql_db.tar.gz *.sql
  24. cd $BAKDIR ;find . -name “*.sql” |xargs rm -rf[ $? -eq 0 ]&&echo “This `date +%Y-%m-%d` RESIN BACKUP is SUCCESS”
  25. cd /data/backup/mysql/ ;find . -mtime +30 |xargs rm -rf

9、自動安裝Nginx腳本,采用case方式,選擇方式,也可以根據實際需求改成自己想要的腳本

C代碼 技術分享
  1. #!/bin/sh
  2. ###nginx install shell
  3. ###wugk 2012-07-14
  4. ###PATH DEFINE
  5. SOFT_PATH=/data/soft/
  6. NGINX_FILE=nginx-1.2.0.tar.gz
  7. DOWN_PATH=http://nginx.org/download/
  8. if[ $UID -ne 0 ];then
  9. echo This script must use administrator or root user ,please exit!
  10. sleep 2
  11. exit 0
  12. fi
  13. if[ ! -d $SOFT_PATH ];then
  14. mkdir -p $SOFT_PATH
  15. fi
  16. download ()
  17. {
  18. cd $SOFT_PATH ;wget $DOWN_PATH/$NGINX_FILE
  19. }
  20. install ()
  21. {
  22. yum install pcre-devel -y
  23. cd $SOFT_PATH ;tar xzf $NGINX_FILE ;cd nginx-1.2.0/ &&./configure –prefix=/usr/local/nginx/ –with-http_stub_status_module –with-http_ssl_module
  24. [ $? -eq 0 ]&&make &&make install
  25. }
  26. start ()
  27. {
  28. lsof -i :80[ $? -ne 0 ]&&/usr/local/nginx/sbin/nginx
  29. }
  30. stop ()
  31. {
  32. ps -ef |grep nginx |grep -v grep |awk ‘{print $2}’|xargs kill -9
  33. }
  34. exit ()
  35. {
  36. echo $? ;exit
  37. }
  38. ###case menu #####
  39. case $1 in
  40. download )
  41. download
  42. ;;
  43. install )
  44. install
  45. ;;
  46. start )
  47. start
  48. ;;
  49. stop )
  50. stop
  51. ;;
  52. * )
  53. echo “USAGE:$0 {download or install or start or stop}”
  54. exit
  55. esac

10、批量解壓tar腳本,批量解壓zip並且建立當前目錄。

C代碼 技術分享
  1. #!/bin/sh
  2. PATH1=/tmp/images
  3. PATH2=/usr/www/images
  4. for i in `ls ${PATH1}/*`
  5. do
  6. tar xvf $i -C $PATH2
  7. done

這個腳本是針對所有tar文件在一個目錄,但是實際情況中,有可能在下級或者更深的目錄,我們可以使用find查找

C代碼 技術分享
  1. #!/bin/sh
  2. PATH1=/tmp/images
  3. PATH2=/usr/www/images
  4. for i in `find $PATH1 -name ”*.tar” `
  5. do
  6. tar xvf $i -C $PATH2
  7. done

如何是zip文件,例如123189.zip 132342.zip 等等批量文件,默認unzip直接解壓不帶自身目錄,意思是解壓123189.zip完當前目錄就是圖片,不能創建123189目錄下並解壓,可以用shell腳本實現

C代碼 技術分享
  1. #!/bin/sh
  2. PATH1=/tmp/images
  3. PATH2=/usr/www/images
  4. cd $PATH1
  5. for i in `find . -name ”*.zip”|awk -F. {print $2} `
  6. do
  7. mkdir -p PATH2$i
  8. unzip -o .$i.zip -d PATH2$i
  9. done

ssh 批量上傳文件

上傳文件大多數用的是ftp,但是用ftp有一點不好,就是本地和遠程的目錄要對應,這樣就要在多個目錄下去切換,這樣挺麻煩的,如果不註意的話,很有可能傳錯。所以想了個辦法利用scp來批量上傳文件或者目錄。

一,scp上傳不要輸入密碼

如果要用scp來上傳文件,第一步就要去掉scp上傳時要輸入密碼。要不然就沒辦法批量上傳了。具體請參考:ssh 不用輸入密碼

二,ssh批量上傳腳本

1,要上傳的文件列表放到一個test文件中

C代碼 技術分享
  1. [email protected]:/home/zhangy# cat test
  2. /home/zhangy/test/aaa
  3. /home/zhangy/test/nginx.conf
  4. /home/zhangy/test/test.sql
  5. /home/zhangy/test/pa.txt
  6. /home/zhangy/test/password

上面就要上傳的文件。

2,批量上傳的腳本

vim file_upload.sh

C代碼 技術分享
  1. #!/bin/sh
  2. DATE=`date +%Y_%m_%d_%H`
  3. if [ $1 ]
  4. then
  5. for file in $(sed ‘/^$/d‘ $1) //去掉空行
  6. do
  7. if [ -f $file ] //普通文件
  8. then
  9. res=`scp $file $2:$file` //上傳文件
  10. if [ -z $res ] //上傳成功
  11. then
  12. echo $file >> ${DATE}_upload.log //上傳成功的日誌
  13. fi
  14. elif [ -d $file ] //目錄
  15. then
  16. res=`scp -r $file $2:$file`
  17. if [ -z $res ]
  18. then
  19. echo $file >> ${DATE}_upload.log
  20. fi
  21. fi
  22. done
  23. else
  24. echo "no file" >> ${DATE}_error.log
  25. fi

上傳成功後,返回的是一個空行,上傳不成功,什麽都不返回

3,上傳的格式

C代碼 技術分享
  1. ./file_upload.sh test 192.168.1.13

test是上傳列表文件,192.168.1.13文件要傳到的地方。

0

轉載請註明
作者:海底蒼鷹
地址:http://blog.51yip.com/linux/1356.html

1. 轉換文件大小寫:

A script to convert the specified filenames to lower case.

C代碼 技術分享
  1. #!/bin/sh
  2. # lowerit
  3. # convert all file names in the current directory to lower case
  4. # only operates on plain files--does not change the name of directories
  5. # will ask for verification before overwriting an existing file
  6. for x in `ls`
  7. do
  8. if [ ! -f $x ]; then
  9. continue
  10. fi
  11. lc=`echo $x | tr ‘[A-Z]‘ ‘[a-z]‘`
  12. if [ $lc != $x ]; then
  13. mv -i $x $lc
  14. fi
  15. done

or

C代碼 技術分享
  1. if test $# = 0
  2. then
  3. echo "Usage $0: <files>" 1>&2
  4. exit 1
  5. fi
  6. for filename in "$@"
  7. do
  8. new_filename=`echo "$filename" | tr A-Z a-z`
  9. test "$filename" = "$new_filename" && continue
  10. if test -r "$new_filename"
  11. then
  12. echo "$0: $new_filename exists" 1>&2
  13. elif test -e "$filename"
  14. then
  15. mv "$filename" "$new_filename"
  16. else
  17. echo "$0: $filename not found" 1>&2
  18. fi
  19. done

2. 看網站 Watch a Website

A script to repeated download a webpage until it matches a regex then notify an e-mail address.

For example to get e-mail when Kesha tickets (not for yourself of course) go on sale you might run:

C代碼 技術分享
  1. % watch_website.sh http://ticketek.com.au/ ‘Ke[sS$]+ha‘ [email protected]
  2. repeat_seconds=300 #check every 5 minutes
  3. if test $# = 3
  4. then
  5. url=$1
  6. regexp=$2
  7. email_address=$3
  8. else
  9. echo "Usage: $0 <url> <regex>" 1>&2
  10. exit 1
  11. fi
  12. while true
  13. do
  14. if wget -O- -q "$url"|egrep "$regexp" >/dev/null
  15. then
  16. echo "Generated by $0" | mail -s "$url now matches $regexp" $email_address
  17. exit 0
  18. fi
  19. sleep $repeat_seconds
  20. done

3. 轉GIF到PNG convert GIF files to PNG

This scripts converts GIF files to PNG files via the intermediate PPM format.

C代碼 技術分享
  1. if [ $# -eq 0 ]
  2. then
  3. echo "Usage: $0 files..." 1>&2
  4. exit 1
  5. fi
  6. if ! type giftopnm 2>/dev/null
  7. then
  8. echo "$0: conversion tool giftopnm not found " 1>&2
  9. exit 1
  10. fi
  11. # missing "in ..." defaults to in "$@"
  12. for f
  13. do
  14. case "$f" in
  15. *.gif)
  16. # OK, do nothing
  17. ;;
  18. *)
  19. echo "gif2png: skipping $f, not GIF"
  20. continue
  21. ;;
  22. esac
  23. dir=`dirname "$f"`
  24. base=`basename "$f" .gif`
  25. result="$dir/$base.png"
  26. giftopnm "$f" | pnmtopng > $result && echo "wrote $result"
  27. done

4. 計數 Counting

A utility script to print the sub-range of integers specified by its arguments.

Useful to use on the command line or from other scripts

C代碼 技術分享
  1. if test $# = 1
  2. then
  3. start=1
  4. finish=$1
  5. elif test $# = 2
  6. then
  7. start=$1
  8. finish=$2
  9. else
  10. echo "Usage: $0 <start> <finish>" 1>&2
  11. exit 1
  12. fi
  13. for argument in "$@"
  14. do
  15. if echo "$argument"|egrep -v ‘^-?[0-9]+$‘ >/dev/null
  16. then
  17. echo "$0: argument ‘$argument‘ is not an integer" 1>&2
  18. exit 1
  19. fi
  20. done
  21. number=$start
  22. while test $number -le $finish
  23. do
  24. echo $number
  25. number=`expr $number + 1` # or number=$(($number + 1))
  26. done

5. 字頻率 Word Frequency

Count the number of time each different word occurs in the files given as arguments.

C代碼 技術分享
  1. sed ‘s/ /\n/g‘ "$@"| # convert to one word per line
  2. tr A-Z a-z| # map uppercase to lower case
  3. sed "s/[^a-z‘]//g"| # remove all characters except a-z and ‘
  4. egrep -v ‘^$‘| # remove empty lines
  5. sort| # place words in alphabetical order
  6. uniq -c| # use uniq to count how many times each word occurs
  7. sort -n # order words in frequency of occurrance

For example

C代碼 技術分享
  1. % cd /home/cs2041/public_html/lec/shell/examples
  2. % ./word_frequency.sh dracula.txt|tail
  3. 2124 it
  4. 2440 that
  5. 2486 in
  6. 2549 he
  7. 2911 a
  8. 3600 of
  9. 4448 to
  10. 4740 i
  11. 5833 and
  12. 7843 the

6. Finding

Search $PATH for the specified programs

C代碼 技術分享
  1. if test $# = 0
  2. then
  3. echo "Usage $0: <program>" 1>&2
  4. exit 1
  5. fi
  6. for program in "$@"
  7. do
  8. program_found=‘‘
  9. for directory in `echo "$PATH" | tr ‘:‘ ‘ ‘`
  10. do
  11. f="$directory/$program"
  12. if test -x "$f"
  13. then
  14. ls -ld "$f"
  15. program_found=1
  16. fi
  17. done
  18. if test -z $program_found
  19. then
  20. echo "$program not found"
  21. fi
  22. done

Alternative implementation using while, and a cute use of grep and ||

C代碼 技術分享
  1. if test $# = 0
  2. then
  3. echo "Usage $0: <program>" 1>&2
  4. exit 1
  5. fi
  6. for program in "$@"
  7. do
  8. echo "$PATH"|
  9. tr ‘:‘ ‘\n‘|
  10. while read directory
  11. do
  12. f="$directory/$program"
  13. if test -x "$f"
  14. then
  15. ls -ld "$f"
  16. fi
  17. done|
  18. egrep ‘.‘ || echo "$program not found"
  19. done

And another implementation using while, and a cute use of grep and ||

C代碼 技術分享
    1. if test $# = 0
    2. then
    3. echo "Usage $0: <program>" 1>&2
    4. exit 1
    5. fi
    6. for program in "$@"
    7. do
    8. n_path_components=`echo $PATH|tr -d -c :|wc -c`
    9. index=1
    10. while test $index -le $n_path_components
    11. do
    12. directory=`echo "$PATH"|cut -d: -f$index`
    13. f="$directory/$program"
    14. if test -x "$f"
    15. then
    16. ls -ld "$f"
    17. program_found=1
    18. fi
    19. index=`expr $index + 1`
    20. done
    21. test -n $program_found || echo "$program not found"
    22. done

Linux常用shell腳本