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

What are the writing specifications for ​ shell

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces what the shell writing specification has, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Shell compiles specifications and strictly abides by these specifications when writing, which not only benefits the writer, but also improves the execution efficiency of users.

1) at the beginning of the script, the script function description, parameter usage description, author name, creation / modification date, and version information should be in the format:

2) when writing a script, pay attention to format alignment, such as alignment of all loops or statements before and after judgment statements, and complete selection of case, such as:

3) execute the following command at the beginning of the script. If an undefined variable is used or the return value of the command is non-zero, an error will be reported directly to exit:

4) it is recommended to put each parameter of the command line in single or double quotation marks, especially those operations such as rm and mv that may modify the existing production data. It is recommended to use the trash bin policy: rm operation is changed to mv operation, file saving directory is established to prevent fallback, and regular cleaning is made:

5) the parameters in the command line need to use'*','?' Wildcards should be based on the most accurate matching principle. If the prefixes, suffixes, extensions and other identifiable keywords of files and directory names can be determined, the information should be included in the parameters. If the length of files and directories can be determined,'?' Wildcards, do not use'*', recommended usage:

Deprecated methods:

Prohibited manner:

6) after assigning a value to a numeric variable, it is necessary to ensure that the value of the variable is numeric, so as to avoid exceptions in subsequent processing:

7) variables used in judgment conditions must be enclosed in double quotes, such as:

Prohibited manner:

8) when packaging and backing up files, you must package them with a relative path, such as:

It is forbidden to enter the full path into the tar package, such as:

9) for files that need to be compressed after packaging, it is recommended to use pipes for processing, such as:

It is not recommended that the two parts be executed separately:

10) when filtering a process using the ps command, if you can determine the user to which the process belongs, you must specify the user name in the parameters, and if its output is used as the input to the kill command, you must specify the user to which the process belongs, such as:

Here is mainly introduced in the daily shell writing encountered more hidden or seemingly simple, but difficult to find the "pit", the preparation should try to avoid using, using better methods to avoid repeating the same mistakes.

1) use update files > not using cp

When using > to modify and roll back a file, retain the subordinate group and permissions of the original file, so as to avoid the permission group being modified when using cp.

2) confirm before using kill

Keyword uses-w exact match field

Keep the site before and after kill, ps-ef twice | grep-w keyword | grep-v grep > > / tmp/kill_ process name _ .backup

Check before deletion to get whether the process number is unique to avoid overkill or manslaughter.

3) confirm before using rm

Backup and delete object information before deletion, avoid using variables, and directly use file and directory names

If it must be used, before deletion, it is recommended to check to avoid erroneous deletion, delete directory and file information to retain:

It is recommended to disable find to search through the root directory and confirm before deletion to avoid multiple deletions or erroneous deletions.

4) pits of For cycle

The in conditions of for loops are distinguished by spaces to avoid entering incorrect or endless loops.

5) taboos of while cycle

If you also want to use variables in the loop, do not use while with pipes.

6) use cp cautiously

This sentence is basically correct, but there is also the problem of space participle. So you should use double quotation marks:

But if the file name happens to start with -, the file name will be treated by cp as a command line option.

Try this one:

But you may also encounter a system that does not support the-- option, so * use the following method:

7) use cd cautiously

Avoid using cd to operate again in the operation directory, which may cause failure to enter the directory and erroneous deletion, such as:

The recommendations are as follows:

8) replace [] with [[]]

When $var is empty, the above command becomes [= "bar"]

Similarly, when $var contains spaces:

[space words here = "var"] both can go wrong. So you should enclose the variable in double quotation marks:

["$var" = var] almost.

However, there is still a problem when $var starts with -. In newer bash, you can use the following methods instead, the [[]] keyword can correctly handle white space, spaces, hyphens, and so on.

Also note that [[applies to strings, if it is a numeric value, use things such as: ($var > 8))

9) do not read and write files at the same time in pipeline operation

You cannot read and write a file at the same time in the same pipe operation. Depending on how the pipe is implemented, the file is either truncated to 0 bytes or grows until the entire hard drive is filled. If you want to change the contents of the original file, you can only write the output to a temporary file before using the mv command.

10) the error-prone problem of cd

Cd may go wrong, causing the command to be executed to be executed in a directory you didn't expect. So be sure to judge the return value of cd.

If you want to execute multiple commands based on the return value of cd, you can use | |.

A bit beside the point about directories, suppose you want to change working directories frequently in shell programs, such as the following code:

How about this:

Parentheses force a child shell to be started so that changing the working directory in this child shell does not affect the parent shell (the shell that executes the script), saving the cd-hassle.

At present, there are more and more automation tools in the line, whether it is the application MAOP or the system SMDB, the automation implementation or the daily operation and maintenance script invocation. Combined with some experience of daily operation and maintenance, the script needs to be more comprehensive and risk control. Here we introduce some script applications combined with operation and maintenance scenarios, hoping to avoid mistakes made in the past and focus on risk control.

1) support the application of interactive script

Interaction is required in many scripts. While avoiding risks, you need to release automated tools to support interaction. You can use expect, as shown in the following example

You can also use the curl tool instead of simple interaction:

# FTP SFTP download

Curl-u ftpuser:ftppassword-O "s ftp://ftp_ip:ftp_port/pathfile"

# FTP SFTP upload

Curl-u ftpuser:ftppassword-- ftp-create-dirs-T upfile "s ftp://ftp_ip:ftp_port/filepath/upfile"

2) script specification execution and log traceability

Directly executed scripts are dangerous, prompting the user how to use the script and logging for tracking.

Examples are as follows:

3) concurrent lock control of scripts

To avoid the exception of simultaneous execution by multiple people or concurrent execution, it is recommended to add a locking mechanism. Examples are as follows:

4) Control the risk of script not exiting

Scripts that are executed frequently need to prevent the script hang from exiting, causing subsequent scripts to be executed again.

5) avoid the risks caused by centrally publishing scripts

When using ftp or sftp to transfer and download files, or centrally access the storage port, increase the hash of the publishing object as much as possible to avoid the impact of storage port congestion caused by centralized operation and alarm of traffic exceeding limits across firewalls.

6) avoid the risk of file growth

When appending data to a file, be sure to set a threshold and empty it if necessary to avoid the increase of the file:

Added a policy to clean up expired files in the directory to avoid generating more and more files, resulting in exhaustion of file nodes:

If there are too many files in the directory, it will be reported that the parameter is too long and the error cannot be deleted. It is recommended to traverse and delete it in a loop:

Thank you for reading this article carefully. I hope the article "what are the shell writing specifications" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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