Common Shell script collection
In O & M, especially for linux O & M, we all know the importance of scripts. scripts will make our O & M more efficient. Therefore, learning to write scripts is a task that every linux O & M personnel must learn, here, we will add the scripts commonly used for linux O & M. The most important thing to learn about scripts is a large number of exercises and practices. Based on the following script, we can expand it so that we can improve it very quickly! The opposite is true!
1. Use Shell programming to determine whether a file is a character device file. If it is copied to the/dev directory.
Reference Program:
C code
- #! /Bin/sh
- FILENAME =
- Echo "Inputfilename :"
- ReadFILENAME
- If [-c "$ FILENAME"]
- Then
- Cp $ FILENAME/dev
- Fi
2. Design a shell program, add a new group named class1, and add 30 users to the group. The username format is stdxx, where xx ranges from 01 to 30.
Reference answer:
C code
- #! /Bin/sh
- I = 1
- Groupaddclass1
- While [$ i-le30]
- Do
- If [$ i-le9]; then
- USERNAME = stu0 $ {I}
- Else
- USERNAME = stu $ {I}
- Fi
- Useradd $ USERNAME
- Mkdir/home/$ USERNAME
- Chown-R$ USERNAME/home/$ USERNAME
- Chgrp-Rclass1/home/$ USERNAME
- I = $ ($ I + 1 ))
- Done
3. Write a shell program to automatically delete 50 accounts. The account name is stud1 to stud50.
Reference Program:
C code
- #! /Bin/sh
- I = 1
- While [$ i-le50]
- Do
- Userdel-rstud $ {I}
- I = $ ($ I + 1 ))
- Done
4. A system administrator needs to do some repetitive work every day. Prepare a solution according to the following requirements:
(1) Delete All subdirectories and all files under the/abc directory;
(2) From ~ At pm, all data in the first domain of each line in the x1 file under the/xyz directory is read to the bak01.txt file under the/backupdirectory;
(3) archive and compress all directories and files under the/data directory as files at every Monday: backup.tar.gz;
(4) uninstall the CD-ROM of the IDE interface at PM (assuming the device name of the CD-ROM is hdc );
(5) Start the instance before a.m.
Reference answer:
Solution:
(1) Use vi to create and edit a crontab file named prgx;
(2) prgx file content:
C code
- 5016 * rm-r/abc /*
- 08-18/1 **** cut-f1/xyz/x1>;/backup/bak01.txt
- 5017 *** tarzcvfbackup.tar.gz/data
- 5517 *** umount/dev/hdc
(3) log on to the Super User and use crontab to execute the content in the prgx file:
Root @ xxx: # crontab prgx; crontab can be automatically started after it is started up before every morning.
5. design a shell program, back up and compress all contents in the/etc directory on the first day of every month, and store them in the/root/bak directory. The file name is in the following format: yymmdd_etc, and yy is a year, mm indicates the month and dd indicates the day. The Shell program fileback is stored in the/usr/bin directory.
Reference answer:
(1) write the shell program fileback:
C code
- #! /Bin/sh
- DIRNAME = 'ls/root | grepbak'
- If [-z "$ DIRNAME"]; then
- Mkdir/root/bak
- Cd/root/bak
- Fi
- YY = 'date + % y'
- MM = 'date + % m'
- DD = 'date + % d'
- Backetc00000000yy1_mm1_dd_etc.tar.gz
- Tarzcvf $ BACKETC/etc
- Echo "filebackfinished !"
(2) Compile the task Timer:
C code
- Echo "001 **/bin/sh/usr/bin/fileback">;/root/etcbakcron
- Crontab/root/etcbakcron
- Or use the crontab-e command to add a scheduled task:
- 01 ***/bin/sh/usr/bin/fileback
6. What should a common user do to regularly back up/user/backup to the/tmp directory at 00:00 every Sunday?
Reference answer:
(1) Method 1:
C code
- You should use the crontab-e command to create the crontab file. The format is as follows:
- 00 ** suncp-r/user/backup/tmp
(2) Method 2:
Create a file in your directory. The file content is as follows:
C code
- 0 ** suncp-r/user/backup/tmp
Then execute crontab file to make it take effect.
7. Design a Shell program and create 50 directories under the/userdata directory, that is, user1 ~ User50, and set the permissions for each directory. the permissions of other users are: read; the permissions of the file owner are: read, write, and execute; and the permissions of the group where the file owner is located are: read and execute.
Reference answer: create a program Pro16 as follows:
C code
- #! /Bin/sh
- I = 1
- While [i-le50]
- Do
- If [-d/userdata]; then
- Mkdir-p/userdata/user $ I
- Chmod754/userdata/user $ I
- Echo "user $ I"
- Let "I = I + 1" (or I = $ ($ I + 1 ))
- Else
- Mkdir/userdata
- Mkdir-p/userdata/user $ I
- Chmod754/userdata/user $ I
- Echo "user $ I"
- Let "I = I + 1" (or I = $ ($ I + 1 ))
- Fi
- Done
8. mysql backs up an instance, automatically backs up mysql, and deletes the backup files 30 days ago.
C code
- #! /Bin/sh
- # Autobackupmysql
- # Wugk2012-07-14
- # PATHDEFINE
- BAKDIR =/data/backup/mysql/'date + % Y-% m-% d'
- MYSQLDB = www
- MYSQLPW = backup
- MYSQLUSR = backup
- If [$ UID-ne0]; then
- EchoThisscriptmustuseadministratororrootuser, pleaseexit!
- Sleep2
- Exit0
- Fi
- If [! -D $ BAKDIR]; then
- Mkdir-p $ BAKDIR
- Else
- EchoThisis $ BAKDIRexists, pleaseexit ....
- Sleep2
- Exit
- Fi
- ### Mysqldumpbackupmysql
- /Usr/bin/mysqldump-u $ MYSQLUSR-p $ MYSQLPW-d $ MYSQLDB>/data/backup/mysql/'date + % Y-% m-% D'/www_db. SQL
- Cd1_bakdir1_tar-czfwww_mysql_db.tar.gz *. SQL
- Cd $ BAKDIR; find.-name "*. SQL" | xargsrm-rf [$? -Eq0] & echo "This 'date + % Y-% m-% d' RESINBACKUPisSUCCESS"
- Cd/data/backup/mysql/; find.-mtime + 30 | xargsrm-rf
9. automatically install the Nginx script. Use the case method. You can also change the script you want based on your actual needs.
C code
- #! /Bin/sh
- ### Nginxinstallshell
- ### Wugk2012-07-14
- ### PATHDEFINE
- SOFT_PATH =/data/soft/
- Nginx_file1_nginx-1.2.0.tar.gz
- DOWN_PATH = http://nginx.org/download/
- If [$ UID-ne0]; then
- EchoThisscriptmustuseadministratororrootuser, pleaseexit!
- Sleep2
- Exit0
- Fi
- If [! -D $ SOFT_PATH]; then
- Mkdir-p $ SOFT_PATH
- Fi
- Download ()
- {
- Cd $ SOFT_PATH; wget $ DOWN_PATH/$ NGINX_FILE
- }
- Install ()
- {
- Yuminstallpcre-devel-y
- Cd $ SOFT_PATH; tarxzf $ NGINX_FILE; cdnginx-1.2.0/&./configure-prefix =/usr/local/nginx/-with-http_stub_status_module-with-http_ssl_module
- [$? -Eq0] & make & makeinstall
- }
- Start ()
- {
- Lsof-I: 80 [$? -Ne0] & amp;/usr/local/nginx/sbin/nginx
- }
- Stop ()
- {
- Ps-ef | grepnginx | grep-vgrep | awk '{print $2}' | xargskill-9
- }
- Exit ()
- {
- Echo $ ?; Exit
- }
- ### Casemenu #####
- Case $ 1in
- Download)
- Download
- ;;
- Install)
- Install
- ;;
- Start)
- Start
- ;;
- Stop)
- Stop
- ;;
- *)
- Echo "USAGE: $0 {downloadorinstallorstartorstop }"
- Exit
- Esac
10. decompress the tar script in batches, decompress the zip file in batches, and create the current directory.
C code
- #! /Bin/sh
- PATH1 =/tmp/images
- PATH2 =/usr/www/images
- Foriin 'ls ${PATH1 }/*'
- Do
- Tarxvf $ I-C $ PATH2
- Done
This script targets all tar files in one directory, but in actual situations, it may be in a lower-level or deeper directory. We can use find to find
C code
- #! /Bin/sh
- PATH1 =/tmp/images
- PATH2 =/usr/www/images
- Foriin 'Find $ PATH1-name "*. tar "'
- Do
- Tarxvf $ I-C $ PATH2
- Done
For example, for batch files such as 123189.zip 132342.zip, unzipdirectly uncompress the image without self-recorded content. The idea is to decompress 123189.zip. The current directory is an image. You cannot create and decompress the 123189 directory. You can use shell scripts.
C code
- #! /Bin/sh
- PATH1 =/tmp/images
- PATH2 =/usr/www/images
- Cd $ PATH1
- Foriin 'Find.-name "*. zip" | awk-F. {print $2 }'
- Do
- Mkdir-pPATH2 $ I
- Unzip-o.polici.zip-dPATH2 $ I
- Done
Original article reprinted, please note: Common Shell scripts in Linux | focus on the Unix/Linux Field
Upload files in batches Using sshMost of the files to be uploaded use ftp, but it is not good to use ftp, that is, to correspond to local and remote directories. In this way, it is very troublesome to switch between multiple directories, if you do not pay attention to it, it is very likely that an error will be reported. So I tried to use scp to upload files or directories in batches.
I. Do not enter a password for scp uploads
If you want to use scp to upload files, you need to enter a password when removing scp from the first step. Otherwise, you cannot upload the files in batches. For details, see:Ssh password is not required
Ii. ssh batch upload scripts
1. Put the list of files to be uploaded into a test file.
C code
- Root @ ubuntu:/home/zhangy # cattest
- /Home/zhangy/test/aaa
- /Home/zhangy/test/nginx. conf
- /Home/zhangy/test. SQL
- /Home/zhangy/test/pa.txt
- /Home/zhangy/test/password
The file to be uploaded.
2. Batch upload scripts
Vim file_upload.sh
C code
- #! /Bin/sh
- DATE = 'date + % Y _ % m _ % d _ % H'
- If [$1]
- Then
- Forfilein $ (sed '/^ $/d' $1) // Remove empty rows
- Do
- If [-f $ file] // common file
- Then
- Res = 'scp $ file $2: $ file' // upload a file
- If [-z $ res] // upload successful
- Then
- Echo $ file >>$ {DATE} _ upload. log // logs of successful upload
- Fi
- Elif [-d $ file] // directory
- Then
- Res = 'scp-r$ file $2: $ file'
- If [-z $ res]
- Then
- Echo $ file >>$ {DATE} _ upload. log
- Fi
- Fi
- Done
- Else
- Echo "nofile" >> {DATE} _ error. log
- Fi
After the upload is successful, an empty row is returned. If the upload fails, nothing is returned.
3. Upload format
C code
- ./File_upload.shtest192.168.1.13
Test is the place where the file 192.168.1.13 is to be uploaded.
0
Reprinted please note
Author: sea bottom e
Address: http://blog.51yip.com/linux/1356.html1. convert file case:
A script to convert the specified filenames to lower case.
C code
- #! /Bin/sh
- # Lowerit
- # Convertallfilenamesinthecurrentdirectorytolowercase
- # Onlyoperatesonplainfiles -- doesnotchangethenameofdirectories
- # Willaskforverificationbeforeoverwritinganexistingfile
- Forxin 'LS'
- Do
- If [! -F $ x]; then
- Continue
- Fi
- Lc = 'echo $ x | tr' [A-Z] ''[a-z]''
- If [$ lc! = $ X]; then
- Mv-I $ x $ lc
- Fi
- Done
Or
C code
- Iftest $ # = 0
- Then
- Echo "Usage $0: <files>" 1> & 2
- Exit1
- Fi
- Forfilenamein "$ @"
- Do
- New_filename = 'echo "$ filename" | trA-Za-Z'
- Test "$ filename" = "$ new_filename" & continue
- Iftest-r "$ new_filename"
- Then
- Echo "$0: $ new_filenameexists" 1> & 2
- Eliftest-e "$ filename"
- Then
- Mv "$ filename" "$ new_filename"
- Else
- Echo "$0: $ filenamenotfound" 1> & 2
- Fi
- Done
2. Watch a Website
A script to repeated download a webpage until it matches a regex then bought y 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 code
- % Watch_website.shhttp: // ticketek.com. au/'ke [sS $] + ha' andrewt @ cse.unsw.edu. au
- Repeat_seconds = 300 # checkevery5minutes
- Iftest $ # = 3
- Then
- Url = $1
- Regexp = $2
- Email_address = $3
- Else
- Echo "Usage: $0 <url> <regex>" 1> & 2
- Exit1
- Fi
- Whiletrue
- Do
- Ifwget-O -- q "$ url" | egrep "$ regexp">/dev/null
- Then
- Echo "Generatedby $0" | mail-s "$ urlnowmatches $ regexp" $ email_address
- Exit0
- Fi
- Sleep $ repeat_seconds
- Done
3. Convert GIF to PNGconvert GIF files to PNG
This scripts converts GIF files to PNG files via the intermediate PPM format.
C code
- If [$ #-eq0]
- Then
- Echo "Usage: $ 0files..." 1> & 2
- Exit1
- Fi
- If! Typegiftopnm2>/dev/null
- Then
- Echo "$0: conversiontoolgiftopnmnotfound" 1> & 2
- Exit1
- Fi
- # Missing "in..." defaultstoin "$ @"
- Forf
- Do
- Case "$ f" in
- *. Gif)
- # OK, donothing
- ;;
- *)
- Echo "gif2png: skipping $ f, notGIF"
- Continue
- ;;
- Esac
- Dir = 'dirname "$ f "'
- Base = 'basename "$ f". gif'
- Result = "$ dir/export base.png"
- Giftopnm "$ f" | pnmtopng> $ result & echo "wrote $ result"
- Done
4. Count 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 code
- Iftest $ # = 1
- Then
- Start = 1
- Finish = $1
- Eliftest $ # = 2
- Then
- Start = $1
- Finish = $2
- Else
- Echo "Usage: $0 <start> <finish>" 1> & 2
- Exit1
- Fi
- Forargumentin "$ @"
- Do
- Ifecho "$ argument" | egrep-v '^ -? [0-9] + $ '>/dev/null
- Then
- Echo "$0: argument '$ argument' isnotaninteger" 1> & 2
- Exit1
- Fi
- Done
- Number = $ start
- Whiletest $ number-le $ finish
- Do
- Echo $ number
- Number = 'expr $ number + 1' # ornumber = $ ($ number + 1 ))
- Done
5. Word Frequency
Count the number of time each different word occurs in the files given as arguments.
C code
- Sed's // \ n/G' "$ @" | # converttoonewordperline
- TrA-Za-z | # mapuppercasetolowercase
- Sed "s/[^ a-Z'] // g" | # removeallcharactersexcepta-zand'
- Egrep-v '^ $' | # removeemptylines
- Sort | # placewordsinalphabeticalorder
- Uniq-c | # useuniqtocounthowmanytimeseachwordoccurs
- Sort-n # orderwordsinfrequencyofoccurrance
For exampleC code
- % Cd/home/cs2041/public_html/lec/shell/examples
- %./Word_frequency.shdracula.txt | tail
- 2124it
- 2440 that
- 2486in
- 2549he
- 2911a
- 3600of
- 4448to
- 4740i
- 5833and
- 7843the
6. Finding
Search $ PATH for the specified programs
C code
- Iftest $ # = 0
- Then
- Echo "Usage $0: <program>" 1> & 2
- Exit1
- Fi
- Forprogramin "$ @"
- Do
- Program_found =''
- Fordirectoryin 'echo "$ PATH" | tr ':''''
- Do
- F = "$ directory/$ program"
- Iftest-x "$ f"
- Then
- Ls-ld "$ f"
- Program_found = 1
- Fi
- Done
- Iftest-z $ program_found
- Then
- Echo "$ programnotfound"
- Fi
- Done
Alternative implementation using while, and a cute use of grep and |
C code
- Iftest $ # = 0
- Then
- Echo "Usage $0: <program>" 1> & 2
- Exit1
- Fi
- Forprogramin "$ @"
- Do
- Echo "$ PATH" |
- Tr': ''\ n' |
- Whilereaddirectory
- Do
- F = "$ directory/$ program"
- Iftest-x "$ f"
- Then
- Ls-ld "$ f"
- Fi
- Done |
- Egrep '.' | echo "$ programnotfound"
- Done
And another implementation using while, and a cute use of grep and |
C code
- Iftest $ # = 0
- Then
- Echo "Usage $0: <program>" 1> & 2
- Exit1
- Fi
- Forprogramin "$ @"
- Do
- N_path_components = 'echo $ PATH | tr-d-c: | wc-C'
- Index = 1
- Whiletest $ index-le $ n_path_components
- Do
- Directory = 'echo "$ PATH" | cut-d:-f $ Index'
- F = "$ directory/$ program"
- Iftest-x "$ f"
- Then
- Ls-ld "$ f"
- Program_found = 1
- Fi
- Index = 'expr $ index + 1'
- Done
- Test-n $ program_found | echo "$ programnotfound"
- Done