Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Shell programming from beginner to proficiency-Chapter 03

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Basic elements of Shell programming

Programming language variable types: variables are important to programming languages, which use variables to store data and perform transportation.

Statically typed language: a language that determines data types during compilation. Most of this is guaranteed by declaring the data type of any variable before using it, such as JAVA and C.

Dynamically typed language: a language that determines data types at run time. It determines the type of a variable when it is assigned to a variable for the first time, such as VBScript and Pthyhon.

Strongly typed language: a language that always enforces type definition without explicit conversion when there is an integer and cannot be treated as a string, such as JAVA and Python.

Weakly typed language: a language in which types can be ignored and integer variables can be treated as strings, such as VBScript and Shell.

As you can see from the example in the figure above, variables in Bash Shell are not type-sensitive.

Among the three variables in shell, the user variable is the most frequently used in the programming process, the location variable is used in the parameter judgment and command return value judgment, and the environment variable is mainly set when the program is running.

User variable: a variable defined by a user during shell programming, divided into local variables and global variables. By default, user-defined variables are global variables, and local variables are defined using the local qualifier. The syntax for variable definition is varname=value. If there can be no spaces on both sides of the equal sign, and the value of the variable is more than one word, you need to enclose the value in quotation marks. When you reference a variable value in a command, you need to precede the variable name with $.

Unset varname can delete variables, but shell returns an error when it encounters an undefined variable, so it is not normally used in this way.

Curly braces operators can use more advanced features of shell string manipulation, that is, string handling operators. It can be done by ensuring that the variable exists and has a value, setting the default value of the variable, capturing errors caused by not setting the variable, and deleting the value portion of the variable that matches the pattern.

Each colon in the above table is optional, and if you omit the colon, change "exist and not null" to "exist" in each definition, that is, the variable operator only determines whether the variable exists.

The pattern matching operator can operate on values, usually used for cutting path names or file name suffixes

The variable substitution in the figure above uses two methods, replacing the colons in the PATH variable with newline characters.

To give another example, if all characters after the equal sign (including the equal sign) are deleted by pattern matching, the output part is the variable name, and all characters before the equal sign (including the equal sign) are deleted, and the output part is the variable value.

The ${# varname} parameter returns the number of characters in the varname value string.

In addition to getting the value of a variable through an assignment statement and through the user giving a variable as a command-line parameter, another method is command substitution. It allows you to use the standard output of a command, just like a variable value, with the syntax `command`, where `is a backquote, and it takes the output of the command as an expression value.

Location variables: also known as system variables, location parameters, are the parameters passed to the script when the shell script is running, and also represent the function parameters within the shll function. Their names are $0 percent 9 after a number, and if they exceed this range, they need to be enclosed in parentheses, that is, ${10}.

In the figure above, there are several common location variables. The number of output variables of $#; $? Output the return value of the previous command; $0 outputs the name of the command; $* outputs all parameters and escapes using\ in double quotes.

The running process of the above program is explained as follows: determine the number of running parameters, if not equal to 2, display the Usage content, $0 represents the script itself; use the grep command to find the $1 string in the $2 file; judge the return value of the previous command, successfully display the relevant information found, and display the echo content if not successful; to display quotation marks in double quotation marks, you need to add\ escape.

Shell has a built-in shift command that "truncates" the leftmost one in the parameter list. After executing shift, the value of $1 will be lost, the value of $2 will be assigned to $1, and so on. The output of $# will also be reduced by one. The shift command defaults to shift 1, which truncates a parameter.

The above example demonstrates the role of shift, passing the file name as an argument to the script, reading one file at a time. In addition, a loop is also used to achieve this function.

Environment variables: variables that affect the running of the current shell process.

The order in which the shell executes commands: when the interactive shell obtains user input, it does not look directly in the PATH path, but looks for the command location in a fixed order. The search order is aliases (alias), keywords (if, for), functions, built-in commands (cd, pwd), external commands (scripts or executable programs, where they are found in the PATH path).

To use a function, you need to follow the following rules: define it first, then use it; allow parameters to be passed to the function by assigning a value to the position parameter, and the function body can use the local qualifier to create a local variable; use the exit command in the function to exit the script, use the return command to return to the place where the function was originally called, and the return command returns the exit status of the last command The built-in command export-f can export the function to a child shell; you can use the source or dot command to load the function saved in another file into the current script; the function can be called recursively without restriction; and you can use declare-f (- F) to find the function defined in the login session.

The function definition is divided into two forms in the above figure, and there is no essential difference between the two. Unset-f funcname can delete a defined function, and-f prompts the unset command to delete a function.

First of all, read the function from the file through the source command, you can call the function as if you were using the command, and then pass the user name as an argument to the function to determine whether the user is online.

The parameters $1 and $2 respectively correspond to the two position parameters of the function, which are added only when the position parameters are obtained inside the function; the return command returns the sum of the two position parameters; the source command reads the function; $? Returns the result of the previous command.

The if/else statement is the simplest process control statement built into shell, which is used to determine that certain commands are executed when a condition is established, often in cases where there are few options.

In the simplest form (without elif and else), the statements statement is executed only if the condition is true; there can be any number of elif, which can choose more conditions and provide more choices, and the else statement executes when the condition of all if and elif is false.

The exit status of a command (function): when each command or function exits, it returns a small integer value to the program that calls it.

In shell's judgment statement, a condition is actually a list of statements rather than a normal Boolean expression. Usually, the exit status 0 indicates that the function or command was executed successfully, and a non-zero number indicates failure.

Shell syntax allows you to logically manipulate exit states, such as NOT,AND and OR.

The NOT operator is!, after the condition condition is determined, use! Reverse, and then test the select execution statement. The AND operator is & &, judge condition1 first, and then judge condition2 after success. If both are successful, the whole judgment statement is successful. The OR operator is |, as long as one of two or more conditions is successful, the entire judgment statement is successful. Both AND and OR are short-circuit operators, that is, as long as the whole statement is judged to be true or false, it is returned directly without continuing the judgment backward, even if the subsequent statement cannot be executed at all.

The only thing an if statement can test is the exit status and cannot be used to detect the value of an expression. But through the test command or [...] At this time, there must be spaces after "[" and "]".

Shell supports string comparison, and the comparison result can be judged by combining the test or [...] command, and then related operations can be performed.

Pass the first position parameter to test.sh, and an error message is displayed when $1 does not exist, but not if $1 exists and is greater than 0. There must be a space between the-s parameter and the file name. The quotation marks around $1 ensure that the program works properly even if it is an empty string.

If the given location parameter is less than 2 or the file specified by $1 does not exist, exit.

The above table shows the commonly used parameters about test.

First of all, it determines whether the file is a directory; if it is not a directory, it determines whether the file exists; if it exists, it determines whether the file has the permission to read and write execution, and if it is passed, the echo statement is displayed; when all the above decisions fail, the echo statement is displayed.

You can use logical operators to concatenate judgment statements with parameters, or you can use logical operators to combine expressions with shell commands.

Case is also a process control structure, and case statements in shell can test strings against patterns that can contain wildcards. You can usually use if-elif statements with test to achieve the same function, but when there are too many choices, it will reflect the limitation that the statement is too long.

As you can see from the syntax, any pattern can be composed of several patterns split by |, in which case the expression matches any one of these patterns and executes the corresponding statement. Pattern matching is performed sequentially until there is a match, and if it cannot be matched, no action is performed.

The case statement, like the fi statement, ends by reverse.

Judge the file suffix, choose different reading methods according to different suffixes, and the last * matches all other mismatched forms, which is equivalent to default in C language.

Loops can control the repetitive behavior of some code or allow operations on multiple objects.

The for loop is used to traverse the entire list of objects / numbers, executing the loop contents of each individual object / number in turn. In the shell script, the object can be a command line argument, a file name, or anything that can be created in a list format.

List is the name list, and each object in the name list is manipulated in the for loop, and the name list can be obtained through operations such as command / pattern matching.

Both examples can traverse the mp3 file and play it in turn. However, using the find command will drill down into the folders one by one, and directly list the folders that will only contain the current directory. Execute the command before the reverse single quotation mark (``), referencing the result as a string. If the in list parameter is omitted in the for loop, it defaults to in "$@", which is the reference list of command line arguments.

The while and until loops in shell are similar to while and do/until in traditional languages, allowing code to run repeatedly when certain conditions are true (or until they are true). The only difference between while and until is how to determine the exit status of condition. In the while statement, the loop continues to run when the exit state of condition is true, otherwise the loop exits, while in the until statement, the loop exits when the exit state of condition is true, otherwise it continues to run. The condition in them can be a simple command / list, or a command that contains & & or | | concatenated commands, just like test in the if statement.

Traversing the PATH path: first assign path; to determine that when path is not empty, use ls-ld to list the first directory in path; then truncate the first directory and colon in path; exit the loop when path is truncated to an empty string (").

While true or until false are often used in shell to build infinite loops. The continue statement is used to start the next loop early in the loop body, the break statement is used to jump out of the loop, and the continue and break statements also make up for the lack of goto in shell. In a multi-tier loop, continue n means to remove the rest of the n-tier code, and break n means to exit the n-tier loop.

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.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report