In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
The editor will share with you how to use the Shell script. I hope you will get something after reading this article. Let's discuss it together.
Preface of shell
Shell can receive the commands entered by the user, and process the commands, and then feedback the results to the user after processing, such as output to the monitor, write to the file, etc., this is the majority of readers' understanding of Shell.
We all know that you can view the contents of the log.txt file by typing the cat log.txt command in Shell, but where is the log.txt on disk? How many data blocks are divided into? Where does it start? Where does it end? How to operate the probe to read it? Shell does not know all these underlying details, it can only call the open () and read () functions provided by the kernel, tell the kernel that I want to read the log.txt file, please help me, and then the kernel obediently follow the instructions of Shell to read the file, and give the contents of the read file to Shell, and finally present it to the user by Shell (in fact, you have to rely on the kernel to present it to the display). Throughout the process, Shell is a "middleman" that "resells" data between the user and the kernel, but the user doesn't know it. The intermediate logic is as follows:
Shell scripts can be combined with many external command-line tools to query information, simplify text processing, schedule task run times, generate reports, and send mail.
Shell is a scripting language
Shell is not a simple stack of commands, we can also program in Shell, which is no different from using common programming languages such as C++, C#, Java, Python, and so on.
Although Shell is not as powerful as C++, Java, Python, etc., it also supports basic programming elements, such as:
If...else selection structure, case...in switch statement, for, while, until loop
Concepts such as variables, arrays, strings, comments, addition, subtraction, multiplication and division, logical operations, etc.
Functions, including user-defined functions and built-in functions (such as printf, export, eval, and so on).
From this point of view, Shell is also a programming language, and its compiler (interpreter) is Shell. What we usually call Shell, sometimes refers to the program that connects the user and the kernel, and sometimes refers to Shell programming.
Shell is mainly used to develop some practical and automated gadgets, but not to develop medium-and large-scale software with complex business logic, such as testing computer hardware parameters, building Web running environment, log analysis and so on. Shell is very suitable.
The proficiency of using Shell reflects the user's mastery of Linux. Operation and maintenance engineers, network administrators, and programmers should all learn Shell.
Especially for Linux operation and maintenance engineers, Shell is an essential skill that must be mastered, which enables us to manage server clusters automatically, otherwise you will have to log in to all servers one by one and set up the same settings for each server, which may be hundreds of thousands, which will waste a lot of time on repetitive work.
Any code must eventually be "translated" into binary form before it can be executed in the computer.
Some programming languages, such as CCompact +, Pascal, Go, assembly, etc., must translate all the code into binary form before the program runs, that is, generate an executable file, and the user gets the final generated executable file without seeing the source code.
This process is called Compile, such a programming language is called compiled language, and the software that completes the compilation process is called Compiler.
Some programming languages, such as Shell, JavaScript, Python, PHP, etc., need to translate while executing, and will not generate any executable files. Users must get the source code to run the program. The program will be translated immediately after running, and part of the translation will be executed. You don't have to wait until all the code has been translated.
This process is called interpretation, such a programming language is called interpretive language or scripting language (Script), and the software that completes the interpretation process is called interpreter.
The advantages of compiled language are fast execution, low hardware requirements and good confidentiality, so it is suitable for the development of operating systems, large-scale applications, databases and so on.
Scripting language has the advantages of flexible use, easy deployment and good cross-platform, which is very suitable for Web development and the production of gadgets.
Shell is a scripting language. After we write the source code, we don't have to compile it, we just run the source code.
How is a shell script built?
We know that shell scripts are executable files with the suffix .sh, and the contents of the executable files are the protagonists we share today.
#! Is the beginning of the shell script, as shown below, and this start is called shebang.
#! / bin/bash
Where / bin/bash is the path of bash
But when we execute shell scripts, we often use operations like. / xxx.sh, but there will also be cases of sh xxx.sh execution, so if the script is executed as a parameter of the sh command, then the shebang line in the script is useless.
In order for shell scripts to run independently, executable permissions are required, and shebang lines must be used for scripts to run independently. It passes through the location #! Then the interpreter runs the script. As for the executable permissions of the script, chmod + x xxx.sh chmod is the command set by permissions under Linux, where the parameter + x means to increase the executable permissions.
Enter the code in hello_shell.sh:
This is the operation procedure and performs the print data effect:
Basic part-variable
Define variable
When you define a variable, the variable name is not marked with a ($) symbol, such as:
Your_name= "James"
Note that there can be no spaces between the variable name and the equal sign, which may be different from all the programming languages you are familiar with. At the same time, the naming of variable names must follow the following rules:
Naming can only use letters, numbers and underscores, and the first character cannot start with a number.
There can be no spaces in the middle, you can use an underscore (_).
You cannot use punctuation.
You cannot use keywords in bash (you can view reserved keywords with the help command).
In addition to explicit direct assignment, you can also use sentences to assign values to variables, such as:
The above statement loops out the file name of the directory under / dev.
Use variables:
To use a defined variable, simply precede the variable name with the $symbol:
Your_name= "James" echo $your_name echo ${your_name}
The curly braces outside the variable are optional and can be added or not.
The curly braces outside the variable name are optional, whether to add them or not, and the curly braces are added to help the interpreter identify the boundaries of the variable, as in the following case:
For skill in Ada Coffe Action Java; do echo "I am good at ${skill} Script" done
If you don't add curly braces to the skill variable and write it as echo "I am good at $skillScript", the interpreter will treat $skillScript as a variable (its value is empty), and the code execution result will not be what we expected.
It is recommended to add curly braces to all variables, which is a good programming habit.
Your_name= "tom" echo ${your_name} your_name= "bob" echo ${your_name}
It's legal to write this way, but note that you can't write $your_name= "bob" on the second assignment, but only add the dollar sign ($) when using variables.
Read-only variable
Using the readonly command, you can define a variable as a read-only variable, and the value of a read-only variable cannot be changed.
The following example attempts to change a read-only variable and reports an error:
#! / bin/bash myUrl= "https://www.google.com" readonly myUrl myUrl=" https://www.baidu.com"
Run the script and the result is as follows:
Delete a variable
Use the unset command to delete a variable. Syntax:
Unset variable_name
The variable cannot be used again after it has been deleted. The unset command cannot delete read-only variables.
Example
#! / bin/sh myUrl= "https://www.baidu.com" unset myUrl echo $myUrl
The execution of the above example will have no output.
Variable type
When running shell, three variables exist at the same time:
1) Local variables are defined in scripts or commands and are only valid in the current shell instance. Other programs started by shell cannot access local variables.
2) Environment variables all programs, including those started by shell, can access environment variables, and some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables if necessary.
3) shell variable shell variable is a special variable set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of shell.
Shell string
Strings are the most commonly used and useful data types in shell programming (apart from numbers and strings, there are no other types to use), strings can be in single quotation marks, double quotation marks, or without quotation marks.
Single quotation mark
Str='this is a string'
Then print it out using echo
Restrictions on single quote strings:
Any character in the single quote will be output as is, and the variable in the single quote string is invalid.
A single quotation mark cannot appear in a single quote string (not even after using escape characters for single quotation marks), but it can appear in pairs and can be used as a string concatenation.
Double quotation marks
Your_name='James' str= "Hello, I know you are\" $your_name\ "!\ n" echo-e $str
The output is as follows:
Hello, I know you are "James"!
Advantages of double quotation marks:
There can be variables in double quotation marks
Escape characters can appear in double quotation marks
Concatenate string
Our_name= "James" # concatenates greeting= "hello,"$your_name" in double quotes! " Greeting_1= "hello, ${your_name}!" Echo $greeting $greeting_1 # concatenates greeting_2='hello in single quotation marks,'$your_name'!' Greeting_3='hello, ${your_name}!' Echo $greeting_2 $greeting_3
The output is as follows:
Get string length
String= "abcd" echo ${# string} # output result is 4
Extract substring
The following example intercepts 4 characters starting with the second character of the string:
String= "james is a great basketball player" echo ${string:1:4} # output ames
Note: the index value of the first character is 0.
Look for substrings
Find the position of the character I or o (calculate which letter appears first):
String= "james is a great basketball player" echo `expr index "$string" mnt` # output 3
Note: in the above script,'is a back quotation mark, not a single quote', don't read it wrong.
Shell array
Bash supports one-dimensional arrays (not multidimensional arrays) and does not limit the size of the array.
Similar to the C language, the subscripts of array elements are numbered starting with 0. The subscript is used to get the elements in the array, which can be an integer or an arithmetic expression whose value should be greater than or equal to 0.
Define array
In Shell, arrays are represented by parentheses, and array elements are separated by a "space" symbol. The general form of defining an array is:
In Shell, arrays are represented by parentheses, and array elements are separated by a "space" symbol. The general form of defining an array is:
Array name = (value 1, value 2. Value n)
For example:
You can also define individual components of an array:
There can be no use of consecutive subscripts, and there is no limit to the range of subscripts.
Read array
The general format for reading array element values is:
${Array name [subscript]}
For example:
Valuen=$ {array_ name[n]}
Use the @ symbol to get all the elements in the array, such as:
Echo ${array_name [@]}
Get the length of the array
Get the length of an array in the same way as you get the length of a string, for example:
#! / bin/bash array_name= (value0 value1 value2) # get the number of array elements length=$ {# array_name [@]} # or length=$ {# array_name [*]} # get the length of a single element of the array lengthn=$ {# array_ name [n]} echo $length $length $lengthn
The output is as follows:
3 3 6
Shell comment
Lines that begin with # are comments and are ignored by the interpreter.
Set multiline comments by adding a # sign to each line, like this:
#-hello world---#
What if you encounter a large piece of code that needs to be commented temporarily and uncommented later in the development process?
It is too hard to add a # symbol to each line. You can enclose the code to be commented in a pair of curly braces and define it as a function. If there is no place to call this function, the code will not be executed, achieving the same effect as the comment.
Multiline comment
Multi-line comments can also use the following format: after reading this article, I believe you have some understanding of "how to use Shell scripts". If you want to know more about it, please follow the industry information channel. Thank you for reading!
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.