Shell_script1, shellscript
1. Introduction 2. read3, computation tool 4. if/then structure 5. while loop 6. for Loop 1. Introduction 1. What is shellshell, the interface on which users interact with the system. Shell is a command interpreter and also a high-level programming language. 2. shell, a common kind of Shell, Bourne shell (/usr/bin/sh or/bin/sh) bourne Again Shell (/bin/bash) C Shell (/usr/bin/csh) K Shell (/usr/bin/ksh) Shell for Root (/sbin/sh) where: bash is widely used in daily work. Bash is also the default Shell of most Linux systems. 3. It has a limitation of 1.1 and requires a lot of resources, especially when the execution speed is high, 1.2 is involved, involving a large number of mathematical calculations 1.3. key applications (databases, websites, etc.) 1.4. design graphics or GUI applications 1.5. and directly access hardware 1.6. development of closed-source applications (relative to open-source) 4. Basic File System: A Linux File System is a hierarchical structure that contains directories and files, root directo Ry), with a slash/to indicate the Directory: is a file containing directory items, each directory item contains a file name: the content of the directory is called a directory item, A directory item contains a file name. Only two types of characters are not allowed to appear in the file name: Slash, empty character (ASCII value 0). The slash is used to separate the file names in the path, NULL characters are used to indicate the end of a path. The length of a file name can usually reach 255 characters. When a series of file names are connected, they are separated by a slash. The path is used to indicate the position of the file. The path starting with a slash is called an absolute path, otherwise, it is a relative path, and the relative path returns a code relative to the current working directory: All commands have a return value, which is expressed by an integer between 0 and. A script is a command, which also has a return value, in addition, the function in the script also has the return value to exit the script. The normal method is to exit with the exit [code] command, for example, exit 0; exit $? Ii. read1. Defining read is a buildin command that mainly assigns values to parameters, similar to scanf in C language. It not only can assign values to variables, but also can assign values to arrays. Its input is not only screen, it can also be the file descriptor 2, the actual operation # read a -- input string, assign the string to the variable a; # echo $ ahello world !! # Read name sex age -- assign values to the three variables at the same time. The input delimiter defaults to the space character zhangsan male 50 # unset name sex age -- delete the variable # IFS = '; '-- change the input Separator of read to'; '# vim test. sh #! /Bin/bashprompt = "Please enter your name: "read-p" $ prompt "nameecho" Greetings $ name "III. computing tool 1. Simple mathematical operations # echo $(1 + 2 ** 2-3*4/5% 6 )) -- output the computing result to the screen # a =$ (1 + 2 ** 2-3*4/5% 6 )) -- assign the calculation result to variable a # (a = 1 + 2 ** 2-3*4/5% 6) -- same as # echo "scale = 3; 10/3 "| bc -- bc calculator; retain the third digit after the decimal point # echo" 2 ^ 10 "| bc -- bc calculator; calculate the 10th power of 2 # awk 'in in {print 1/3} '-- calculate awk 2. Obtain the random number # od-N4-tu4/dev/urandom | sed-n'1s /. * // P' -- get a 7-digit number # od-Ad-w24-tu4/dev /Urandom -- obtain a random number # od-tu8/dev/urandom -- obtain a random number # od-tu8/dev/urandom | sed-r's/^ [0-9] + \ s + // '| sed-r's/\ s +/\ n/G' | cut-b1-8 | sed-r-n'/^. {8} $/P' | sed's/^/186/'| head-n5000 | vi--- get 10 thousand phone numbers # od-N40000-tu4/dev/urandom | sed-r's/^ [0-9] + (\ s + )? // '| Sed-r's/\ s +/\ n/G' | grep-vE' ^ \ s * $ '> 10k_random -- generates 10 thousand random numbers # sed- r-n'/^. {8} $/p '10k_random | head-n 100000 | sed's/^/186/'> phone_num3. Obtain the number sequence # seq 10 -- Obtain 1 to 10 # seq 1 2 10 -- get 1 to 10, step Size: 2 # seq 10 100 -- get 10 to 100 # seq 10-1 1 -- reverse order, 10 to 1 4. if/then instance 1. Determine whether the character "a" is equal to "A" # vim test. sh #! /Bin/baslif [["a" = "A"]; thenif ["a" = "A"]; then echo "a equals A" else echo "a no equals A" fi2. Determine/root/test. whether sh exists and has executable permissions # vim test. sh #! /Bin/baslif test-x/root/test. sh; then echo "/root/test. sh is executable "fi3. Determine whether the system has a root user # vim test. sh #! /Bin/basconditioned grep-E -- color = auto ^ root:/etc/passwd; then echo "user root exists" fi4. Determine the file type # vim test. sh #! /Bin/bashfunction isSymbolicLink () {file = $1 flag =$ (ls-ld $ file | cut-b1) test "$ flag" = "1" return $ ?} File = $ 1if isSymbolicLink $ file; then echo "Symbolic Link" elif test-d $ file; then echo "Directory file" elif test-f $ file; then echo "Regular file" elif test-B $ file; then echo "Block special" elif test-c $ file; then echo "Character special" elif test-p $ file; then echo "Named pipe" elif test-S $ file; then echo "Socket" else echo "Unkown" fi5. determine the size of the input number # vim test. sh #! /Bin/bashnum = $ 1if test "$ num"-lt 10; then echo "small number" elif test "$ num"-lt 20; the number "elif test" $ num "-lt 30; then echo" big number "else echo" super large number "fi6. Get a number from the standard input, and output the specified string # vim test. sh #! /Bin/bashecho-n "Enter a number:" read numif ["$ num"-lt 100]; thenecho "less than 100" elif ["$ num"-ge 100-a "$ num"-lt 200]; thenecho "greater than or equal to 100 less than 200" elif ["$ num"-ge 200-a "$ num"-lt 300]; thenecho "greater than or equal to 200 less than 300" elseecho "other numbers" fi 5. wihle loop 1. Identify the return code of the command after the while keyword test. If the condition is true, the program reads the commands in the while LOOP body; 0 is true. The loop body is as follows: while [] -- while: run the [] command to test the return code of the [] command cat/filename | while read line -- while: run the read command, the return code of the read command do ...... done2, loop control statement continue -- terminate the current loop, start the next loop break -- terminate the current loop, and exit the loop body exit -- terminate the current script 3, instance # vim test. sh -- difference between continue and break #! /Bin/bashwhile truedosleep 1 echo testcontinue/breakechodone # vim test. sh -- differentiate break from exit #! /Bin/bashwhile test-e/data/test. shdoecho "exists" sleep 1 break/exitdoneecho "loop end" # vim test. sh -- search for the given path until it reaches #! /Bin/baslif test $ #-ne 1; thenecho "wrong paraneter"> & 2 exitfipath = $1 while test! -E "$ path" dosleep 1 echo "don't found !!! "Doneecho" found "# vim test. sh -- the specified time when the script runs. It exits as soon as the time reaches. The unit is s #! /Bin/basffe test $ #-ne 1; thenecho "Usage: $ (basename $0) TIME "> & 2 exit 1 fitimeLength = $1 beginTime = $ (date + % s) endTime = $ ($ beginTime + $ timeLength )) --------------------------------------------------------- while test $ (date + % s)-lt "$ endTime" doecho "processing ..... "sleep 1done --------------------------------------------------------- while truedoif test $ (date + % s)-ge" $ endTime "; thenbreakfiecho" pro Cessing... "sleep 1done ------------------------------------------------------------- echo" time out "# vim test. sh -- cyclically read each row of the file and calculate the number of characters in each line #! /Bin/bashfile = $1 ----------------------------------------------------------- totalLines = $ (wc-l <$ file) line = 1 while test $ line-le $ totalLinesdolineData =$ (sed-n "$ {line} p" $ file) len = $ (echo-n $ lineData | wc-c) echo "line $ {line}: $ len" line = $ ($ line + 1 )) done --------------------------------------------------------- line = 1 while read lineDatadolen = $ (echo $ lineData | wc-c) echo "line $ {line}: $ len" line = $ ($ Line + 1) done <$ file ----------------------------------------------------------- # vim test. sh -- print out 10 rows of hello world; <(seq 10) is equivalent to a file path; it is called process replacement #! /Bin/bashwhile read numdoecho "hello world" done <(seq 10) when n = 1 while [$ n-le 10] doecho "hello world" n = $ (n + 1) done --------------------------------------------------------- # vim test. sh -- create an endless loop, which must be automatically terminated after 1 minute of cyclic Operation #! /Bin/bashstart_time = $ (date + % s) while truedocur_time = $ (date + % s) test $ (cur_time-start_time )) -ge 10 & breaktime =$ (cur_time-start_time) echo "time is $ time ...... "sleep 1 done # vim test. sh -- first create 100.txt files in the while loop; then change the suffix of all files. html #! /Bin/bashcount = 100 --------------------------------------------------------- seq $ count | while read idotouch contains invalid iplus.txt donels-1 *. txt | while read oldnamedonewname = $ (echo $ oldname | sed's /. txt $ /. html/') mv $ oldname $ newnamedone when while read idotouch when using iplus.txt done <(seq $ count) while read oldnamedonewname = $ (echo $ oldname | sed's /. txt $ /. html/') mv $ Oldname $ newnamedone <(ls-1 *. txt) # vim test. sh -- calculates the even number of sums within 1000. You cannot use pipelines because pipelines generate sub-processes #! /Bin/bashsum = 0 while read numdosum = $ ($ sum + $ num) done <(seq 2 2 998) echo "sum: $ sum" # vim test. sh -- add 100 email users in batches. The username is u1 to u100, the password is abc, and the logon shell is/sbin/nologin, which only belongs to the email group #! /Bin/bashpassword = abcgroup = emailgrep-Eq "^ $ {group }: "/etc/group | groupadd $ groupwhile read idouseradd u $ {I}-N-g $ group-s/sbin/nologinpasswd u $ {I} -- stdin <" $ password "done <(seq 100) # vim test. sh -- batch Delete the first 100 Email users created just now #! /Bin/bashwhile read idouserdel-r u $ {I} done <(seq 100 6. The for loop is in a series of strings separated by delimiters, one of which is obtained each time in order, after a string is retrieved, the string retrieved at the end of the Loop will be saved in a variable. You can use the separator to separate the string in the loop body by the following methods: 1. manually enter a string for the specified number of cycles # vim test. sh #! /Bin/bashfor I in 1 2 3 doecho $ idon2, the string provided by the variable # vim test. sh #! /Bin/bashFILES = "/bin/bash/bin/ls/bin/cat" for file in $ FILES doecho $ filedone3, string generated by the Program # vim test. sh #! /Bin/bashfor n in $ (seq 11) do echo $ ndone4, generated by shell expansion, file in the loop directory # vim test. sh #! /Bin/bashfor f in/etc/init. d/* doecho $ fdone # vim test. sh5. Print the names of all files starting with loop under/dev # vim test. sh #! /Bin/bashfor file in/dev/loop * doecho $ (basename $ file) done6, calculate the even number within 1000 and # vim test. sh #! /Bin/bashsum = 0for number in $ (seq 2 2 998) do sum = $ ($ sum + $ number) doneecho "total: $ sum "7. Add 100 mail users in batches. The username is u1 to u10, the password is abc, and the logon shell is/sbin/nologin, which only belongs to the email group # vim test. sh #! /Bin/bashfunction checkGid () {gid = $ 1if! Grep-qE "^ $ gid:"/etc/group; thengroupadd $ gidfi} function isRoot () {id = $ (id | awk-F "[= (]" '{print $2}') if test "$ id"-ne 0; thenecho "must be root"> & 2 exit 1fi} count = 10 namePrefix = upassword = abcshell =/sbin/nologingid = emailisRootcheckGid $ gidfor num in $ (seq $ count) doname =$ {namePrefix }$ {num} useradd $ name-s $ shell-g $ gid &>/dev/nullif test $? -Ne 0; thenecho "failed to create $ name"> & 2 elseecho "created successfully -- $ name" echo "$ password" | passwd -- stdin $ name &>/dev/nullif test $? -Ne 0; thenecho "failed to change password for $ name"> & 2 elseecho "password changed successfully -- $ name" fifidone8. obtain the corresponding table of IP addresses and MAC addresses of all computers in the LAN # vim test. sh #! /Bin/bashipPrefix = 192.168.1.startIp = 1 endIp = 254for num in $ (seq $ startIp $ endIp) doip =$ {ipPrefix} $ numping-W1-c1 $ ip &>/dev/null & donewaitarp-n | sed '/incomplete/d' | awk' {print $1, $3} '| cat | sort-n-t '. '-k4, 4 | column-t9, print the 9-9 multiplication table # vim test. sh #! /Bin/bashfor row in $ (seq 9) dofor col in $ (seq $ row) doecho-n "$ {col} x $ {row} = $ ($ col * $ row)" doneechodone | column-t10, simple calculator #! /Bin/bashvarnum = 3if test "$ #"-ne "$ varnum "; thenecho "wrong argument"> & 2 exit 1finum1 = $1num2 = $3 operator = $ 2if test "$ operator" = "x "; thenoperator = "*" fiif test "$ operator" = "/"-a "$ num2" = 0; thenecho "division by 0"> & 2 exit 1 firesult =$ ($ num1 $ operator $ num2) echo "$ result" NOTE: Multiplication processing; processing When the divisor is 0 11. Copying some files under the specified directory to the specified directory requires: #1. the command line parameters receive two parameters: the source directory and the target directory #2. if the source directory does not exist, the error #3. if the target directory does not exist, create #4. if the target already exists but does not If the file is a directory, an error is reported. #5. copy only regular files and soft link files. #6. For regular files, only files smaller than 1 MB are copied. # vim/test. sh #! /Bin/bashfunction displayHelp () {echo "Usage: $ (basename $0) srcdir dstdir"} function getSize () {file = $1 size = $ (ls-l $ file | awk '{print $5}') echo $ size} if test $ #-ne 2; thendisplayHelp> & 2 exit 1 fisrcdir = $1 dstdir = $ 2if test! -D "$ srcdir"; thenecho "$ srcdir not exists or is not a directory"> & 2 exit 1 fiif test! -E "$ dstdir"; thenmkdir "$ dstdir" fiif test! -D "$ dstdir"; thenecho "$ dstdir is not a directory"> & 2 exit 1 folder or file in $ srcdir/* doif test-L $ file; thencp-a $ file $ dstdir/elif test-f $ file; then --------------------------------------------------- size = $ (getSize $ file) if test "$ size"-lt 1048576; thencp-a $ file $ dstdir/fi ready find $ file-type f-size-1024 k-exec cp-a {}$ dstdir/\; ------------------------------------------------- fidone