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 reliable suggestions for Shell scripting

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to talk to you about the reliable suggestions for Shell scripting, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following for you. I hope you can get something from this article.

1. Specify bash

The first line of the shell script, #! What should it be after that? If you ask others this question, different people may have different answers.

I've seen / usr/bin/env bash, also seen / bin/bash, and / usr/bin/bash, and / bin/sh, and / usr/bin/env sh. This can be regarded as the four ways to write the word 'fennel' in the programming world.

In most cases, the above five writing methods are equivalent. However, anyone who has written a program knows that unexpected holes are often hidden in "a few cases".

What if the default shell for the system is not bash? For example, for a version of a Linux distribution, the default sh is not bash.

What if the bash of the system is not / usr/bin/bash?

I recommend / usr/bin/env bash and / bin/bash. The former adds a middle tier through env and asks env to search for bash; in $PATH. The latter is officially endorsed, with the established bash location, and / usr/bin/bash is just a symbolic link to it.

2. Set-e and set-x

OK, after some discussion, the first line is now settled. Isn't it time to start writing the second line?

Wait a minute! Before you start to conceive and write down the specific code logic, insert a line set-e and a line set-x.

Set-x prints out what is executed when each line of shell script is executed. It allows you to see the current execution, and the variables involved will be replaced with the actual values.

Set-e ends the program when an execution error occurs, just like "throwing an exception" in other languages. (to be exact, not all errors end the program, see the note below)

Note: the conditions for set-e to end the program are complicated. In man bash, a paragraph is used to describe all kinds of situations. Most execution exits on error, unless the shell command is in the following situations:

A non-ending part of a pipeline, such as error | ok

The non-ending part of a combined statement, such as ok & & error | | other

The non-ending part of a series of statements, such as error; ok

Located in the judgment statement, including test, if, while, and so on.

The combination of these two can save you a lot of time when you debug. For the sake of defensive programming, it is necessary to insert them before writing the first line of specific code. Ask yourself, how many times can you write right at once when writing code? Most code, before committing, usually goes through the process of debugging and modifying repeatedly. Instead of introducing these two configurations at a time of anxiety, leave room for debug in the first place. After the code can finally be submitted, it's not too late to consider whether to keep it.

3. Bring shellcheck.

Well, now I have three lines of (boilerplate) code, and I haven't written any specific business logic. Is it time to start writing?

Wait a minute! If you want to do good work, you must first sharpen its tools. This time, I will introduce a shell scripting artifact: shellcheck

Ashamed to say, although I have been writing shell scripts for several years, I still can't remember some grammars. At this time, we have to rely on the guidance of shellcheck. In addition to alerting syntax problems, shellcheck can also detect bad code that is common to shell scripting. Originally, there are a few of my N suggestions about these bad code, but considering that shellcheck can discover these problems, I took pains to rule them out. There is no doubt that using shellcheck has brought a huge leap forward in my shell writing skills.

The so-called "standing on the shoulders of giants", although we recruits, skills are not as strong as veterans, but we can catch up with each other in equipment! If you use your hands to install it, you will be able to get to know a seductive "teacher". Why not?

By the way, shellcheck is actually written in haskell. Who says haskell can only be used to pretend to be a pussy?

4. Variable expansion

In shell scripts, you can occasionally see this practice: echo $xxx | awk/sed/grep/cut... . It looks like a big situation, but you just want to change the value of a variable. Why use a cow knife to kill a chicken? Bash's built-in variable expansion mechanism is enough to meet your needs! It's the same old way, read the fancifuk manaul! Man bash then searches for Parameter Expansion, and here are the tips you want.

5. Pay attention to local

As you write more and more code, you begin to refine the repetitive logic into functions. There's a chance you'll fall into a hole in bash. In bash, variables are global by default without the local qualifier. Variables default to global-this is similar to js and lua; by contrast, few bash tutorials tell you this fact at the beginning. In the top-level scope, it doesn't matter whether it is a global variable or not. But in a function, declaring a global variable can contaminate other scopes (especially if you don't notice it at all). So, for variables declared within the function, be sure to add the local qualifier.

6. Trap signal

If you have ever written a slightly more complicated program that runs in the background, you should know what a "signal" is in the posix standard. If you don't know, just read the next paragraph. Like other languages, shell supports signal processing. Trap sighandler INT can call the sighandler function when it receives a SIGINT. The way other signals are captured, and so on.

However, the main application scenario of trap is not which signal to capture. The trap command supports "capturing" many different processes-specifically, allowing users to inject function calls into specific processes. The most commonly used of these are trap func EXIT and trap func ERR.

Trap func EXIT allows functions to be called at the end of the script. Because the registered function can be called regardless of whether it exits normally or abnormally, I use it to register the cleanup function in scenarios where I need to call a cleanup function, rather than simply calling the cleanup function at the end of the script.

Trap func ERR allows functions to be called when there is an error in running. A common technique is to use the global variable ERROR to store error information, and then complete the corresponding error report based on the stored value in the registered function. Centralizing the otherwise fragmented error handling logic in one place can sometimes work wonders. Keep in mind, however, that when a program exits abnormally, both EXIT-registered functions and ERR-registered functions are called.

7. Look before you leap

The above are all specific suggestions, while the remaining two are more practical.

The name of this suggestion is "look before you leap". In fact, no matter what code you write, even if it's just an auxiliary script, think twice and don't be careless. No, keep that in mind when writing scripts. After all, many times, a complex script starts with a few lines of small commands. The person who wrote the script at first may have thought it was an one-time task. It is inevitable that some external conditions are assumed in the code, which may be normal at the time, but as the external environment changes, these become hidden reefs. To make matters worse, few people test the script. Unless you run it, you don't know if it will work properly.

To slow down the decay of script code, you need to identify what becomes dependent and which is essential for the script to run properly. Have proper abstraction and write changeable code; at the same time, have a sense of defensive programming and give your code a moat.

8. make best use of the advantages and bypass the disadvantages

In some cases, writing scripts in shell means that it is difficult to migrate, to handle errors uniformly, and to process data cleanly.

Although the use of external commands can easily and quickly achieve a variety of complex functions, but as the opposite of coins, they have to rely on grep, sed, awk and other tools to glue them together.

If there is a need to be compatible with multiple platforms, be careful to avoid bizarre pitfalls such as differences in BSD and GNU coreutils,bash versions.

Due to the lack of complete data structures and consistent API,shell scripts, it is incompetent to deal with complex logic.

Use the right tools to solve specific problems. Knowing when to use shell and when to switch to another more general scripting language (such as ruby/python/perl) is also the secret of writing reliable shell scripts. If your task can be accomplished by combining common commands and involves only simple data, then the shell script is the right hammer. If your task contains complex logic and complex data structures, you need to write scripts in a language such as ruby/python.

After reading the above, do you have any further understanding of the reliable suggestions for Shell scripting? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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

Development

Wechat

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

12
Report