LinuxShell Scripting Best Practices
IT Curbside
Preface
As with any coding specification, this is not just about the beauty of the coding format, but also about conventions and coding standards. This document focuses mainly on the rules we generally follow, and we try to avoid providing comments on those that are not explicitly mandatory.
Coding standards are particularly important to programmers for several reasons:
The guidelines in this document are intended to maximize the following:
Note: Anything not explicitly stated is mandatory by default
The main references are the following:
This document is intended to maximize the following:
These are the rules that we have in place. p>
Shell is only recommended for use as a relatively simple utility or wrapper script. Therefore, individual shell scripts should not be too complex.
The following principles should be followed when choosing when to use shell scripts:
Executables are not recommended to have extensions, and library files must have a .sh extension and should be non-executable.
Executing a program without knowing the language in which it was written, and shell scripts are not required to have extensions, so it is preferred that executables have no extensions.
Library files, on the other hand, are important to know the language in which they are written, and the use of .sh as a language-specific extension distinguishes them from library files written in other languages.
Filenames should be all lowercase and can contain either an underscore _ or a hyphen -, hyphens are recommended for executables and underscores for libraries.
Positive example:
Counter-example:
Source files are encoded in UTF-8. Avoiding the different ways that different operating systems handle line breaks in files, LF is used.
Maximum of 120 characters per line. The underlying reason for the maximum length limit per line of code is that excessively long lines can cause dyslexia, making indentation ineffective.
With two exceptions:
If there is a string that must be longer than 120 characters, try to make it as short as possible by using a suitable method such as a heredocument or embedded line breaks.
Example:
Besides the use of line breaks at the end of lines, spaces are the only whitespace characters allowed in source files.
Methods, variables, etc. that are never used or commented out should be firmly cleaned out of the code to avoid interference from too much garbage.
Bash is the only executable script shell allowed.
Executables must start with #! /bin/bash at the beginning. Please use set to set the shell’s options so that with bashecho “Process$:Donemaking$$$.”
#Example 7: Command arguments and paths without quotes grep-liHugo/dev/”$1″
#Example 8: Regular variables in double quotes, special cases where ccs may be empty can be left unquoted gitsend-email —to “${reviewers}”${ccs:+”–cc””${ ccs}”}
#Example 9: regular single quotes, $1 may be null without quotes grep-cP'([Ss]special||?characters*)${1:+”$1″}
#Example 10: positional parameter passing is recommended to use “$@” with quotes, and all parameters are passed as a single string using “$*” with quotes. quoted “$*”#contentoft.shfunc_t{echonum:$#echoargs:1:$12:$23:$3}
func_t”$@”func_t”$*”#When executing . /t.shabc the output is as follows: num:3args:1:a2:b3:cnum:1args:1:abc2:3:
Use $(command) instead of backquotes.
Because backquotes require backslashes to escape internal backquotes if they are to be nested. Nesting in the form of $(command) does not require escaping and is more readable.
Positive example:
Converse example:
Conditional tests
Use [[…]] , instead of [,test, and /usr/bin/[.
Because there is no path expansion or word slice between [[ and ]], using [[…]] can reduce the number of mistakes made. And [[…]] supports regular expression matching, while […]] does not. Refer to the following example:
Use variable references instead of string filtering whenever possible.
Bash can handle empty string tests very well, please use empty/non-empty string test methods instead of filtering characters to make the code more readable. Positive Example:
Counter Example:
Positive Example:
Counter Example:
Positive Example:
Filename Expansion
When doing wildcard expansions of filenames, please specify an explicit path.
When directories have special filenames such as files beginning with -, use the extended wildcard with path . /* is much safer than * without a path.
The use of eval should be avoided.
Eval modifies the input when used to assign variables, but setting variables does not check what those variables are. Counter-example:
Please use process substitution or a for loop rather than connecting a while loop through a pipe.
This is because in a while loop after a pipe, the commands are run in a child shell, so changes to variables are not passed to the parent shell.
This implicit subshell in a pipelined while loop makes bug localization very difficult. Counter-example:
If you are sure that the input does not contain spaces or other special symbols (usually not from user input), you can use a for loop instead. For example:
Redirecting output can be accomplished using process substitution. but put the commands into an explicit subshell rather than an implicit subshell created by a while loop. for example:
Always check the return value and provide a useful return value.
For non-piped commands. use $? or check directly via an if statement to keep it concise.
For example:
When built-in commands can accomplish the same task, between shell built-in commands and calling external commands, you should try to choose the built-in command.
Built-in commands create fewer dependencies than external commands, and in most cases calling built-in commands will result in better performance than calling external commands (which usually incur additional process overhead).
Positive example:
Counter-example:
Loading external library files is not recommended. , it is recommended to use source to improve readability. Positive example:
Counter-example:
Unless it is necessary, try to use a single command and its parameter combinations to accomplish a task, rather than unnecessary combinations of multiple commands plus pipes. Commonly discouraged uses are for example: cat and grep together to filter strings; cat and wc together to count lines; grep and wc together to count lines, etc.
Positive examples:
Except in special cases, almost all functions should not use exit to exit the script directly, but should use return so that errors can be handled in subsequent logic. Positive example:
Counter-example:
The following tools are recommended to help us with code specification:
Original link: http://itxx00.github.io/blog/2020/01/03/shell-standards/
Scripting’s – text messages Bomber
Script of — QQ WeChat Bomber
ansible — one click to set up redis5.0.5 cluster
elk7.9 true cluster docker deployment documents
The world’s most complete loki deployment and configuration documents
Strongest Security Hardening Scripts 2.0
One click setup iptbales script
The student letter of those things of the seventh – Linux basic shell scripting h3>
Following the previous track, the next is the Linux shell scripting learning. This is very, very important for the subsequent processing of large amounts of (massive more appropriate) data for the engineers of the letter is very, very important, but again, as a bit of a curmudgeon, for a long time for the “script” what I have been dead on the meaning of. Mostly, I found it a bit abstract, especially when discussing the analytical part of a project with my colleagues at Sangshin, who would often say that it was a self-explanatory term in their minds, not realizing that for the layman (like me), it was an unrelenting “curse of knowledge”. Often, I pretend to understand, and then move on to the next question, forming a vague impression.
Baidu’s explanation is: script (Script) is an extension of the batch file, is a plain text program, generally speaking, the computer script program is to determine a series of control of the computer to carry out arithmetic operations in which the combination of the action can be realized in a certain logical branch. I don’t know if you can understand it, but I really didn’t when I started.
The explanation of Bird’s Private Kitchen is: shellscript is a “program” written using the shell’s functionality, this program is to use a plain text file to write some of the shell’s syntax and commands (including external commands) in it, with regular expressions, pipeline commands, and redirection of data streams and other functions to achieve what we want to deal with. purposes. It’s not clear, it’s like you can’t understand it any more —-
Jude’s simple, brutal, vernacular explanation is that scripting is the combination of many commands in Linux according to certain rules in order to achieve a specific function. there are a lot of simple commands in Linux that tend to be simple conversations, for example, cd is just to go into a certain directory, it’s simple and straight forward. But what if I want to go into some directory A, and then create directory B in directory A, and then create text C in directory B? Of course you can do this step by step, and if you want to do it all in one step, then you can use a script that writes the three commands together and executes them together. It seems a bit wordy —-
Or from an English perspective, the English equivalent of script is Script, and the Chinese definition of this word also means script. Script is good to understand ah, the script is the director (raw letter engineers) based on a main idea (to achieve the goal) in accordance with certain techniques (rules) written a story. No matter which actor, he or she has to act according to the script. So, learning English is also helpful for the birth of a letter~
According to the complexity of the script can be divided into:
This needless to say, in fact, is a number of simple commands in order, the execution of the script will be in accordance with the command before and after the relationship between the front and back of the implementation of a one-by-one.
As opposed to a simple basic script, a structured command script can exert logical flow control, thereby changing the order in which programs (commands) are executed. Commands in a basic script are executed from top to bottom, but a structured command script can repeat or skip certain commands based on logical judgment.
Commonly used structured commands (statements) are:
Followed by what nested loops ah what, but I think the above 7 commands to learn home, should be able to cope with most of the applications in the raw letter analysis.
Remember when I was in high school, the physics teacher (also the class teacher) explained to us the exercises when there is an interesting routine: no matter what the problem is now written under a “answer:” to show their determination to solve the problem, but also a kind of positive psychological implication. Scripting is also a trick, but in general it’s relatively simple.
For simple scripts (the super-simple kind), you can just link a few commands together, separated by a “;”.
For longer and more complex scripts, you generally need to create a text and edit in it. This involves a text editor, the more common and simple ones are generally nano and vim, which are really simple and the rules are easy to understand, and tutorials are readily available without much ado.
For example, after creating a script with vim, the specific syntax (set of rules):
ok, the script is written, how do you get the script to start working? This has to do with the environment variables and relative and absolute paths that we talked about before. There are three ways:
That’s it, you should feel it a little bit, the rest is just practicing furiously and practicing furiously~