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

How to write Linux Shell script

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

Share

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

This article mainly shows you "how to write Linux Shell script", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to write Linux Shell script" this article.

Code style specification

It starts with a "snake stick."

The so-called shebang actually appears as "#!" in the * * lines of many scripts. At the beginning of the comment, he indicates the default interpreter when we do not specify an interpreter, which may be as follows:

#! / bin/bas

Of course, there are many kinds of interpreters, except for bash, we can check the natively supported interpreters with the following command:

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

When we directly use. / a.sh to execute this script, if there is no shebang, it will default to the interpreter specified by $SHELL, otherwise it will use the interpreter specified by shebang.

However, the above writing may not be very adaptable, and we usually specify it in the following way:

#! / usr/bin/env bash

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 so easy to understand, it can be especially big to maintain without comments.

The meaning of comments is not only to explain the purpose, but to tell us what to pay attention to, just like a README.

Specifically, for shell scripts, comments generally include the following sections:

Shebang

Parameters of the script

The purpose of the script

Considerations for script

Script writing time, author, copyright, etc.

Notes before each function

Some more complex single-line command comments

Parameters should 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 an appropriate echo to facilitate users to understand the use of parameters.

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

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

Variables and magic numbers

In general, we define some important environment variables at the beginning to ensure the existence of these variables.

Source / etc/profileexport PATH= "/ usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/apps/bin/"

This definition has a very common use, and the most typical application is that when we have many versions of java installed locally, we may need to specify a java to use. At this point, we will redefine the JAVA_HOME and PATH variables at the beginning of the script for control.

At the same time, a good piece of code usually does not have many "magic numbers" hard-coded in the code. If it has to be, it is usually defined at the beginning in the form of a variable, and then the variable is called directly when it is called, which is convenient for future modification.

There are rules for indenting

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

In fact, the correct indentation is very important, especially when writing functions, otherwise it is easy to confuse the function body with directly executed commands when reading.

The common indentation methods are "soft tab" and "hard tab".

Soft tab is indented with n spaces (n is usually 2 or 4).

The so-called hard tab of course refers to the real "" character.

Here do not tear which way *, can only say that each has its own advantages and disadvantages. Anyway, I'm used to using hard tab.

For things like if and for statements, let's * Don't write the keywords then,do on a separate line, it looks ugly.

There is a standard for naming.

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

File name specification, ending in .sh, easy to identify

Variable names should have meaning and not be misspelled

Uniform naming style. Shell is usually written in lowercase letters with underscores.

Coding should be unified

Try to use UTF-8 coding when writing scripts, which can support some strange characters such as Chinese. However, although I can write Chinese, I still try to write in English when writing comments and typing log. After all, many machines still do not support Chinese directly, and there may be garbled codes when typed.

It is also important to note that when we write a shell script with utf-8 coding under windows, we must pay attention to whether the utf-8 has BOM. By default, windows determines the utf-8 format by adding three EF BB BF bytes to the beginning of the file, but there is no BOM by default in Linux. So if we are writing scripts under windows, we must be careful to change the code to Utf-8 without BOM, which can be changed with editors such as notepad++. Otherwise, the first three characters will be recognized when running under Linux, reporting some errors that do not recognize the command.

Remember to add permissions.

Although this is very small, I often forget that it is a bit annoying that no enforcement authority will lead to direct execution.

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 this script is for users to use directly on the command line, then we also need to be able to echo the execution process in real time during execution, making it easy for users to control.

Sometimes in order to improve the user experience, we will add some special effects to the echo, such as color, flicker and so on. Please refer to the introduction of this article in ANSI/VT100 Control sequences.

Password to be removed

Don't hard-code passwords in scripts, don't hard-code passwords in scripts, don't hard-code passwords in scripts.

Say the important thing three times, especially when the script is hosted on a platform like Github.

It's too long to have a branch.

When calling some programs, the parameters may be very long, so in order to ensure a better reading experience, we can use the backslash to branch:

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

Notice that there is a space before the backslash.

Coding detail specification

Code efficiency

When using the command, we should understand the specific practice of the command, especially when the amount of data processing is large, we should always consider whether the command will affect the efficiency.

For example, the following two sed commands:

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

They all serve the same purpose of getting the * lines of the file. However, the * command reads the entire file, while the second command reads only the * * lines. When the file is large, just one different command can make a huge difference in efficiency.

Of course, this is just to give an example, the really correct use of this example should be to use the head-N1 file command.

Frequently use double quotation marks

Almost all bosses recommend adding double quotes when using "$" to get variables.

Not adding double quotation marks can cause a lot of trouble in many cases. Why? To give an example:

#! / bin/sh # it is known that the current folder has a file var= "* .sh" echo $var echo "$var" of a.sh

The results of his operation are as follows:

A.sh*.sh

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

Echo * .shecho "* .sh"

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

Skillful use of main function

We know that compiled languages like java,C have a function entry, and this structure makes the code very readable, and we know which ones are executed directly and which are functions. But the script is different, the script is an interpretive language, from * line to * line, if the command and function are mixed together, it is very difficult to read.

Friends who use python know that a standard python script generally looks like this:

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

He uses an ingenious way to implement the main function we are used to, making the code more readable.

In shell, we have a similar tip:

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

We can use this method of writing and also implement similar main functions to make the script more structured.

Consider scope

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

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

His output is 2 instead of 1, which is obviously not in line with our coding habits and can easily cause some problems.

Therefore, instead of using global variables directly, we * use commands like local readonly, and secondly we can use declare to declare variables. These approaches are better than using a global definition.

Function return value

When using a function, it must be noted that the return value of a function in shell can only be an integer. It is estimated that in general, the return value of a function usually represents the running state of the function, so it is usually 0 or 1 is enough, so it is designed like this. However, if you have to pass a string, you can also use the following workarounds:

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

In this way, you can pass some extra parameters through things like echo or print.

Indirect reference value

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

VAR1= "2323232" VAR2= "VAR1"

We have a variable VAR1 and a variable VAR2, and the value of this VAR2 is the name of VAR1, so what should we do now if we want to get the value of VAR1 through VAR2?

The way to compare hillbilly is as follows:

Echo ${! VAR1}

This usage is indeed feasible, but it looks very uncomfortable, it is difficult to just understand, we do not recommend it. And in fact, we don't recommend using the eval command ourselves.

The more comfortable way to write it is as follows:

Echo ${! VAR1}

By adding one to the variable name! You can do a simple indirect reference.

However, it should be noted that with the above method, we can only take values, not assign values.

Skillful use of heredocs

The so-called heredocs can also be regarded as a method of multi-line input, that is, in "

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