In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
Shell scripts and commonly used loop sentences, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
one。 What is shell and its function
Shell literally is a "shell", a bridge between the operating system (kernel) and the user, acting as a command interpreter, translating commands entered by the user to the system for execution. Like DOS under Windows, shell in Linux provides some built-in commands (shell commands) for users to use, which can be used to write shell scripts to accomplish complex and repetitive tasks.
What is a script?
A script is made up of Shell commands, which are the names of executable programs that can be run without compilation. It runs through an interpreter, so it is relatively slow.
Advantages of shell scripting
1. The important basis of automatic management
two。 Important work of tracking and management system
3. Simple detection function
4. Simplification of continuous instructions
5. Simple data processing
6. Cross-platform support and short learning process
Considerations for writing shell scripts
The execution of instructions is analyzed and executed from top to bottom and from left to right.
Instructions are issued as mentioned earlier: multiple spaces between instructions, options, and parameters are ignored.
The blank line will also be ignored, and the blank pushed by the [tab] button is also considered a blank key.
If an Enter symbol (CR) is read, try to start executing the line (or string) command
If there is too much content on one line, you can use "[Enter]" to extend to the next line
"#" can be used as a note! Any data added after # will be ignored as a comment!
Executing the shell script is divided into four points
Direct instruction: the shell.sh must have readable and executable (nx) permissions, and then:
Absolute path: use / home/dtsai/shell.sh to issue instructions
Relative path: use .shel.sh to execute assuming the working directory is / home/dmtsai/,
* variable "PATH" function: place shell.sh in the directory specified by PATH, for example: ~ / bin/
Execute as a bash program: execute through "bash shell,sh" or "sh shell.sh"
two。 Simply edit shell [root@localhost ~] # vim a.shangxinxbinbinbashecho-e "hellow\ a\ n" exit 0 [root@localhost ~] # chmod axix a.sh [root@localhost ~] # sh a.sh hellow
The first line #! / bin/bash declares the shell name used by this script:
Description of the content of the program:
Declaration of major environment variables: it is recommended that some important environment variables be set, and I personally think that PATH and LANG (if you use relevant information to output) are the most important of them! In this way, we can issue some external instructions directly when this program is going on, without having to write an absolute path.
Just write the main program in the main program part.
The execution result informs (defines the echo value) whether the execution of an instruction is successful or not, you can use $? To observe this variable, then we can also use the exit instruction to interrupt the program and send a value back to the system.
\ a sound of warning;\ nWrap and the cursor moves to the beginning of the line
Conversation script: the content of the variable is determined by the user
Changing with date: using date to create parts
Numerical operation: simple addition, subtraction, multiplication and division
Conversation script: the content of the variable is determined by the user
[root@localhost ~] # vim b.shroud Please input your lastname binhread-p "Please input your firstname:" firstnameread-p "Please input your lastname:" lastnameecho-e "\ nYour full name is: ${firstname} ${lastname}" [root@localhost ~] # sh b.sh Please input your firstname: xPlease input your lastname: aYour full name is: X a
Changing with date: using date to create parts
[root@localhost ~] # vim x.shrunken pound Bash echo-e "I will use 'touch' command to create 3 files." Read-p "Please input your filename:" fileuserfilename=$ {fileuser:- "filename"} date1=$ (date-- date='2 days ago' +% Y%m%d) date2=$ (date-- date='1 days ago' +% Y%m%d) date3=$ (date +% Y%m%d) file1=$ {date1} ${filename} ${date2} file3=$ {filename} ${date3} touch "${file1}" touch "${file2}" touch "${file3}" filename: a [root@ Localhost ~] # ls\\ you can see the 20191203 20191205 a.sh initial-setup-ks.cfg public video file music 20191204 anaconda-ks.cfg b.sh x.sh template picture download desktop that has been created for 3 days.
Numerical operation: simple addition, subtraction, multiplication and division
[root@localhost ~] # vim q.shroud charger binhecho-e "You SHOULD input 2 numbers, I will multiplying them!\ n" read-p "first number:" firstnuread-p "second number:" secnutotal=$ ((${firstnu} * ${secnu}) echo-e "\ nThe result of ${firstnu} x {secnu} is = = > ${total}" [root@localhost ~] # sh q.sh You SHOULD input 2 numbers, I will multiplying them! First number: 2second number: 3The result of 2 x 3 is = > 6
Using the testing function of test instruction
three。 Loop statement
If conditional test statement
The if conditional test statement allows the script to automatically execute the corresponding commands according to the actual situation. From a technical point of view, if statements are divided into single-branch structure, double-branch structure and multi-branch structure, and their complexity increases step by step with flexibility.
The single branch structure of 1.if conditional statement is composed of if, then and fi keywords, and the preset command is executed only after the condition is established, which is equivalent to the colloquial "if. So." . The single branch if statement belongs to the simplest conditional judgment structure.
Case study:
[root@localhost ~] # vim x.sh #! / bin/bashread-p "Please input (Y):" ynif ["${yn}" = = "Y"] | | ["${yn}" = = "y"]; thenecho "OK, continue" exit 0fiif ["${yn}" = = "N"] | | ["${yn}" = = "n"]; thenecho "Oh, interrupt!" Exit 0fiecho "I don't know what your choice is" & & exit 0 [root@localhost ~] # sh x.sh Please input (Y hand N): YOK, continue [root@localhost ~] # sh x.sh Please input (Y hand N): NOh, interrupt! [root@localhost ~] # sh x.sh Please input (Y hand N): asdI don't know what your choice is
The double branch structure of 2.if conditional statement is composed of if, then, else and fi keywords. It makes a condition matching judgment, and if it matches the condition, it executes the corresponding preset command; otherwise, it executes the default command in the case of mismatch, which is equivalent to the colloquial "if. Then... or... so..." . The double branch structure of if conditional statement is also a very simple judgment structure.
Https://s1.51cto.com/images/blog/201809/17/e6093221273e0d416b0ee944c5e318c4.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
Also use the above case:
[root@localhost ~] # vim x.shanzhao binbinhread-p "Please input (Y):" ynif ["${yn}" = = "Y"] | | ["${yn}" = = "y"]; thenecho "OK, continue" elif ["${yn}" = = "N"] | ["${yn}" = "n"] Thenecho "Oh, interrupt!" elseecho "I don't know what your choice is" fi [root@localhost ~] # sh x.sh Please input (YampN): YOK, continue
The multi-branch structure of 3.if conditional sentence is composed of if, then, else, elif and fi keywords. It makes multiple condition matching judgments, any of which will execute the corresponding preset command after the match is successful, which is equivalent to the colloquial "if. Then. Then." . The multi-branch structure of if conditional statement is the most commonly used conditional judgment structure in work, which is relatively complex but more flexible.
Case study:
[root@localhost ~] # vim a.shemag binba ["${1}" = = "hello"]; thenecho "Hello, how are you?" elif ["${1}" = ""] Thenecho "You MUST input parameters, ex > {${0} someword}" elseecho "The only parameter is' hello', ex > {${0} hello}" fi [root@localhost ~] # sh a.sh\\ you can see that parameters must be added to execute You MUST input parameters, ex > {a.sh someword} [root@localhost ~] # sh a.sh helloHello, how are you?
Using if... Then: network statu
[root@localhost ~] # vim netstat. I will detect your Linux server's services! "echo-e" The www, ftp, ssh, and mail (smtp) will be detect!\ n "testfile=/dev/shm/netstat_checking.txtnetstat-tuln > ${testfile} testing=$ (grep": 80 "${testfile})\\ detect whether if exists on port 80 [" ${testing} "! ="] Thenecho "WWW is running in your system." fitesting=$ (grep ": 22" ${testfile})\\ detects whether if exists on port 22 ["${testing}"! = "]; thenecho" SSH is running in your system. "fitesting=$ (grep": 21 "${testfile})\\ detects whether if exists on port 21 [" ${testing} "! ="] Thenecho "FTP is running in your system." fitesting=$ (grep ": 25" ${testfile}) if ["${testing}"! = "]; thenecho" Mail is running in your system. "fi [root@localhost ~] # sh netstat.sh Now, I will detect your Linux server's serviceshands the www, ftp, ssh, and mail (smtp) will be detect! SSH is running in your system. \\ see ssh running Mail is running in your system on the system. \\ Mail service is running in the system
For conditional loop statement
The for loop statement allows the script to read multiple messages at once and then manipulate the information one by one. When there is a range of data to be processed, the for loop statement is perfect.
For...do...done (fixed cycle)
Case study:
Suppose I have three kinds of animals, dog, cat, and elephant, and I want to output each line like this: "There are dogs..." And so on, you can:
[root@localhost ~] # vim w.shfor animal in dog cat elephantdoecho "There are ${animal} s...." done [root@localhost ~] # sh w.sh There are dogs.... There are cats.... There are elephants....
While conditional loop statement
While conditional loop statement is a kind of statement that makes the script execute the command repeatedly according to certain conditions. Its loop structure often does not determine the number of final execution before execution, which is completely different from the targeted and wide-ranging usage scenarios in for loop statements. The while loop statement determines whether to continue executing the command by judging whether the conditional test is true or not. If the condition is true, it continues to execute, and if it is false, it ends the loop.
While... Do...done,until...do...done (indefinite cycle)
While: loop only when the latter conditions are met
Until: loop only when the latter condition is not met
Case study:
Suppose I want to ask the user to type yes or YES to end the execution of the program, otherwise I will always tell the user to enter the string.
[root@localhost ~] # vim s.shallop OK you input the correct answer. ["${yn}"! = "yes"-a "${yn}"!! = "YES"] doread-p "Please input yes/YES to stop this program:" yndoneecho "OK! you input the correct answer." [root@localhost ~] # sh s.sh Please input yes/YES to stop this program: asdPlease input yes/YES to stop this program: asdPlease input yes/YES to stop this program: YESOK! You input the correct answer.
Case conditional test statement
The case statement matches the data in multiple ranges, executes the command and ends the entire conditional test if the match is successful, and executes the default command defined in the asterisk (*) if the data is not in the listed range.
Take advantage of case.... Esac judgment
[root@localhost ~] # vim aa.shangxue binbinhcase ${1} in "hello") echo "Hello, how are you?"; ") echo" You MUST input parameters, ex > {${0} someword} "; *) echo" Usage ${0} {hello} ";; esac [root@localhost ~] # sh aa.sh You MUST input parameters, ex > {aa.sh someword} [root@localhost ~] # sh aa.sh helloHello, how are you?
In general, using the syntax "case $variable in", there are roughly two ways to get that "$variable":
Direct drop: for example, as mentioned above, use "script.sh variable" to directly give the contents of the $1 variable, which is how most programs are designed in the / etc/init.d directory.
Interactive: use the read instruction to let the user enter the contents of the variable.
Let the user type one, two, three, and display the user's variables on the screen, if not one, two, three, inform the user that there are only these three options.
[root@localhost ~] # vim bb.shroud Input your choice: "choice#case ${choice} incase ${1} in" one ") echo" Your choice is ONE ";;" two ") echo" Your choice is TWO ";;" three ") echo" Your choice is THREE " *) echo "Usage ${0} {one | two | three}";; esac [root@localhost ~] # sh bb.sh This program will print your selection! Usage bb.sh {one | two | three} [root@localhost ~] # sh bb.sh oneThis program will print your selection! Your choice is ONE [root@localhost ~] # sh bb.sh twoThis program will print your selection! Your choice is TWO
Function
Definition of function
There are two syntax formats for defining functions in shell, which are:
Function name ()
{
Command sequence
}
Or:
The function function name () / function may not be written.
{
Command sequence
}
After the function is defined, the user can call it directly in shell without ()
Call syntax function name parameter 1, parameter 2. The variables in the function are global variables, there is no local variable function call can pass parameters, in the function with $1 # 2, $3. To reference the passed parameters.
Also use the above case: using function calls to implement
[root@localhost ~] # vim cc.shrunken echo Bash function printit () {echo-n "Your choice is"} echo "This program will print your selection!" Case ${1} in "one") printit; echo ${1} | tr 'Amurz' 'Amurz'\\ convert the case of parameters;; "two") printit; echo ${1} | tr'aMuz''Amurz';; "three") printit Echo ${1} | tr'amurz 'Amurz'; *) echo "Usage ${0} {one | two | three}";; esac [root@localhost ~] # sh cc.sh This program will print your selection! Usage cc.sh {one | two | three} [root@localhost ~] # sh cc.sh oneThis program will print your selection! Your choice is ONE [root@localhost ~] # sh cc.sh twoThis program will print your selection! Your choice is TWO
Tracking and debug of Shell script
Options and parameters for sh execution:-n: do not execute script (script), only query syntax questions-v: before executing script, output the contents of the script to the screen-x: display the contents of the used script to the screen
Case study:
[root@localhost ~] # sh-n aa.sh\\ normal [root@localhost ~] # sh-v aa.sh\\ output to the screen #! / bin/bashcase ${1} in "hello") echo "Hello, how are you?"; "echo" You MUST input parameters, ex > {${0} someword} "; *) echo" Usage ${0} {hello} " EsacYou MUST input parameters, ex > {aa.sh someword} [root@localhost ~] # sh-x cc.sh\\ the output screen + echo 'This program will print your selection!' This program will print your selection! + case ${1} in+ echo 'Usage cc.sh {one | two | three}' Usage cc.sh {one | two | three} is helpful to you after reading the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.