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 is the Shell script programming specification in linux?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article mainly introduces what is the Shell script programming specification in linux, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

Code Style Specification

It starts with "snake stick."

Shebang is actually the first line of many scripts with #! The initial comment, which indicates the default interpreter when we do not specify one, might be something like this:

#!/ bin/bash

Of course, there are many kinds of interpreters, in addition to bash, we can use the following command to check the native supported interpreters:

$ cat /etc/shells #/etc/shells: valid login shells /bin/sh /bin/dash /bin/bash /bin/rbash /usr/bin/screen

When we use directly./ When a.sh executes this script, it defaults to using the interpreter specified by $SHELL if there is no shebang, otherwise it uses the interpreter specified by shebang.

This is the way we recommend it.

The code has comments.

Comments are obviously common sense, but again, this is especially important in shell scripts. Because many single-line shell commands are not easy to understand, maintenance without comments can be particularly head-scratching.

Comments are not just meant to explain the purpose, but to tell us what to look for, like a README.

Specifically, for shell scripts, comments typically consist of the following sections:

shebang

Parameters for script

The purpose of the script

Notes for scripts

Script writing time, author, copyright, etc.

Description comments before each function

Some of the more complex one-line command comments

Parameters to be standardized

This is very important, when our script needs to accept parameters, we must first determine whether the parameters are in line with the specification, and give appropriate echo, so that users can understand the use of parameters.

At least, at least, we have to judge the number of parameters:

if [[ $# != 2 ]];then echo "Parameter incorrect. " exit 1 fi

Variables and magic numbers

In general, we will define some important environment variables at the beginning to ensure that these variables exist.

source /etc/profile export PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/apps/bin/"

This definition has a very common use, the most typical application is when we have many java versions installed locally, we may need to specify a java to use. Then we will redefine JAVA_HOME and PATH variables at the beginning of the script to control it. Also, a good piece of code usually doesn't have a lot of hard-coded magic in it. If there must be, it is usually defined in the form of a variable at the beginning, and then the variable is called directly when it is called, so that it is convenient to modify it later.

There are rules for indenting

For shell scripts, indentation is a big problem. Because many places that need to be indented (such as if,for statements) are not long, many people are too lazy to indent, and many people are not used to using functions, resulting in indentation function is weakened.

In fact, correct indentation is very important, especially when writing functions, otherwise we can easily confuse the function body with the command directly executed when reading.

Common indentation methods are mainly "soft tab" and "hard tab" two kinds.

A soft tab is indented with n spaces (n is usually 2 or 4)

Hard tabs, of course, are real\t characters.

Here do not tear which way is best, can only say that each has its own advantages and disadvantages. I am used to hard tabs anyway.

For if and for statements, we'd better not write then and do keywords on a separate line, which looks ugly.

There are standards for naming

The so-called naming convention basically includes the following points:

File name specification, ending in.sh for easy identification

Variable names should have meaning, not misspelled

Uniform naming style, shell generally written with lowercase letters underlined

Coding should be unified

When writing scripts, try to use UTF-8 encoding to support some strange characters such as Chinese. However, although you can write Chinese, you should try your best to write comments and log in English. After all, many machines still don't directly support Chinese, so there may be garbled characters when typing out. Here, we also need to pay special attention to one point, that is, when we use utf-8 code to write shell scripts under windows, we must pay attention to whether this utf-8 has BOM. By default windows determines utf-8 format by adding three EF BB BF bytes to the beginning of the file, but in Linux the default is no BOM. Therefore, if we are writing scripts under windows, we must pay attention to changing the code to Utf-8 without BOM, which can be changed by editors such as notepad++. Otherwise, when running under Linux, it will recognize the first three characters, thus reporting some errors that cannot recognize the command. Of course, one of the more common problems with cross-platform scripting is that the line breaks are different. Windows default is\r\n and unix is\n. However, there are two widgets that can easily solve this problem: dos2unix,unix2dos.

Remember to add permissions

Although this point is very small, but I personally often forget that without execution permission will lead to direct execution, a bit annoying.

Log and echo

Needless to say, the importance of the log can facilitate us to go back and correct errors, which is very important in large projects.

If the script is intended to be used directly from the command line, then it would be nice to be able to echo execution in real time for user control.

Sometimes to improve the user experience, we will add some special effects to the echo, such as color, flashing, etc., see ANSI/VT100 Control sequences for details.

Password to be removed

Don't hardcode passwords in scripts, don't hardcode passwords in scripts, don't hardcode passwords in scripts.

Important things are said three times, especially when scripts are hosted on platforms like Github.

Too long to branch

When calling some programs, the parameters may be very long. In this case, in order to ensure a better reading experience, we can use backslashes to branch:

./ configure \ –prefix=/usr \ –sbin-path=/usr/sbin/nginx \ –conf-path=/etc/nginx/nginx.conf \

Notice the space before the backslash.

Code Detail Specification

code efficiency

When using commands, you should understand the specific practices of commands, especially when the data processing volume is large, and always consider whether the command will affect efficiency.

For example, the following two sed commands:

sed -n '1p' file sed -n '1p;1q' file

They both do the same thing, getting the first line of the file. But the first command reads the entire file, while the second command reads only the first line. When files are large, just one command can make a huge difference in efficiency.

Of course, this is just an example. The correct way to use this example is to use the head -n1 file command.

Use double quotes frequently

Almost all big shots recommend double quotes when using "$" to get variables.

Not adding double quotes can cause a lot of trouble in many cases. Why? Take an example:

#!/ bin/sh #The current folder is known to have an a.sh file var="*.sh" echo $var echo "$var"

His results are as follows:

a.sh *.sh

Why is this happening? In fact, it can be explained that he carried out the following orders:

echo *.sh echo "*.sh"

In many cases, when variables are used as parameters, be sure to pay attention to this point and carefully appreciate the differences. The above is just a very small example, and there are too many problems caused by this detail in practice...

Skillful use of main function

We know that compiled languages like Java and C have a function entry, and this structure makes the code readable, and we know which ones are directly executed and which ones are functions. But scripts are different. Scripts are interpreted languages. They are executed directly from the first line to the last line. If commands and functions are mixed together in this, it is very difficult to read.

Python friends know that a standard Python script is roughly at least something like this:

#!/ usr/bin/env python def func1(): pass def func2(): pass if __name__=='__main__': func1() func2()

He implemented the main function we are used to in a very clever way, making the code more readable.

In the shell, we have a similar trick:

#!/ usr/bin/env bash func1(){ #do sth } func2(){ #do sth } main(){ func1 func2 } main "$@"

We can write this way and implement a similar main function to make the script more structured.

Consider Scope

The default variable scope in the shell is global, such as the following script:

#!/ usr/bin/env bash var=1 func(){ var=2 } func echo $var

His output result is 2 instead of 1, which obviously does not conform to our coding habits and easily causes some problems.

Therefore, rather than using global variables directly, we are better off using commands like local readonly, and secondly we can declare variables using declare. These are better than global definitions.

function return value

When using a function, be sure to note that the return value of a function in the shell can only be an integer. It is estimated that because the return value of a function usually indicates the running state of the function, it is generally 0 or 1, so it is designed like this. However, if you have to pass a string, you can do the following workaround:

func(){ echo "2333" } res=$(func) echo "This is from $res. "

In this way, some extra parameters can be passed through echo or print.

indirect reference value

What is indirect quotation? For example, the following scenario:

VAR1="2323232" VAR2="VAR1"

We have a variable VAR1 and a variable VAR2. The value of VAR2 is the name of VAR1. So we want to get the value of VAR1 through VAR2. What should we do at this time?

The way to compare them is this:

eval echo \$$VAR2

What does that mean? In fact, it is to construct a string echo XXX, this XXX is XXX", this XXX is the value VAR1 of VAR2, and then use eval to force parsing, so as to achieve a disguised value.

This usage works, but it seems uncomfortable and difficult to understand intuitively, and we don't recommend it. And in fact we don't recommend eval.

The following is a list of the most popular languages:

echo ${! VAR1}

By prepending the variable name with one! You can do simple indirect references.

However, it should be noted that with the above method, we can only do the value, but not the assignment. If you want to do the assignment, you have to use eval to deal with it honestly:

VAR1=VAR2 eval $VAR1=233 echo $VAR2

Use heredocs skillfully

Heredocs can also be regarded as a multi-line input method, that is, in the "

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