Do you know some 10 not-so-known bash functions?

Introduction

One of my previous articles was more popular than I expected, so I want to write another article to introduce some lesser-known bash features

As I said before, because I think bash is a technology that needs to be used frequently (and need to be understood), I wrote a book while studying bash. Although many people are not familiar with bash, but I think they also think it is very important enough to be gratifying.

Do you know some 10 not-so-known bash functions?

1) ^ x ^ y ^

A little trick I always use.

Have you never entered a similar command?

$ grp somestring somefile-bash: grp: command not found

Hey, this command is wrong, so you have to type "↑", then type "←" until "p", and then type "e" to execute.

Or enter it like this:

$ ^ rp ^ rep ^ grep 'somestring' somefile $

One detail you may need to pay attention to is:

$ grp rp somefile $ ^ rp ^ rep ^ $ grep rp somefile

If you want to search for "rep", then you have to delve into the man page and learn to use this more powerful command:

$ grp rp somefile $ !!: gs / rp / repgrep rep somefile $

I will not explain this usage here. . .

2) pushd / popd

This is very useful in scripts, especially in loops

As shown below, suppose you are writing a for loop that enters and exits the folder:

for d1 in $ (ls -d * /) do # Store original working directory. original_wd = "$ (pwd)" cd "$ d1" for d2 in $ (ls -d * /) do pushd "$ d2" # Do something popd done # Return to original working directory cd "$ {original_wd}" done

You can use the pushd stack to rewrite the above code like this:

for d1 in $ (ls -d *) do pushd "$ d1" for d2 in $ (ls -d * /) do pushd "$ d2" # Do something popd done popddone

It can track and record the directory you switch and push or pop the stack

Note that when an error occurs when using pushd, the stack record may be lost and popd multiple times. So you may want to use set -e in the script (see previous article)

Of course you can also use cd-, but it will not use the stack-just return to the previous directory

cd ~ cd / tmpcd blahcd-# Back to / tmpcd-# Back to 'blah'cd-# Back to / tmpcd-# Back to' blah '...

3) shopt vs set

These two commands bothered me for a while.

What is the difference between the two?

Set has been introduced in the previous article, and the shopt looks similar. Just typing shopt will display a series of options:

$ shoptcdable_vars offcdspell oncheckhash offcheckwinsize oncmdhist oncompat31 offdotglob off

I found some answers here.

Fundamentally, there seems to be a series of bash (and other shells) built on top of sh, and adding the shopt command provides a way to set additional shell options

But I'm not sure ... if you know why, please tell me.

4) Here Docs and Here Strings

"Here Docs" are files created with some statements in the shell.

The "trick" is simple. Define a word for ending, then all input lines that appear before this word alone will constitute a file.

like this:

$ cat> afile here is a doc> it has three lines> SOMEENDSTRING alone on a line will save the doc> SOMEENDSTRING $ cat afilehere is a docit has three linesSOMEENDSTRING alone on a line will save the doc $

note:

· If the ending word does not appear "alone" on a line, it can constitute a file

· SOMEENDSTRING is usually END, but this is just a habit

Lesser known is "here string":

$ cat> asd

5) Operation of string variables

In the past, you might have written code as shown below, using tools such as sed to manipulate strings:

$ VAR = 'HEADERMy voice is my passwordFOOTER' $ PASS = "$ (echo $ VAR | sed 's / ^ HEADER (. *) FOOTER / 1 /')" $ echo $ PASS

But you may not know that bash itself is possible.

This means you can save a lot of sed and awk.

One way to rewrite the above code is as follows:

$ VAR = 'HEADERMy voice is my passwordFOOTER' $ PASS = "$ {VAR # HEADER}" $ PASS = "$ {PASS% FOOTER}" $ echo $ PASS

· # Means "match and delete the given pattern string from the beginning of the string"

·% Means "match and delete the given pattern string from the end of the string"

On my computer, the latter method is twice as fast as the previous one. And (to my surprise), his speed is roughly equivalent to the speed of python scripts with similar functions

If you want to use wildcard (see above) mode string and adopt greedy mode, you need to double write:

$ VAR = 'HEADERMy voice is my passwordFOOTER' $ echo $ {VAR ## HEADER *} $ echo $ {VAR %% * FOOTER}

6) The default value of the variable

These are very useful for writing scripts.

If you have a variable that has no value assigned, you can "assign default value" to it like this

Create a default.sh file and write the following:

#! / bin / bashFIRST_ARG = "$ {1: -no_first_arg}" SECOND_ARG = "$ {2: -no_second_arg}" THIRD_ARG = "$ {3: -no_third_arg}" echo $ {FIRST_ARG} echo $ {SECOND_ARG} echo $ {THIRD_ARG}

Now execute chmod + x default.sh and run the script with ./default.sh first second:

Observe how the default value of the third parameter is assigned instead of the first two.

You can also directly use $ {VAR: = defaultval} (equal sign, not dash), but note that this does not apply to position variables in scripts or functions. Try to modify the above script to see how it failed.

7) Traps

When a signal is sent to the script, the built-in trap can be used to "capture"

Here is an example I used in my chepci script:

function cleanup () {rm -rf "$ {BUILD_DIR}" rm -f "$ {LOCK_FILE}" # get rid of / tmp detritus, leaving anything accessed 2 days ago + find "$ {BUILD_DIR_BASE}" / * -type d- atime +1 | rm -rf echo "cleanup done"} trap cleanup TERM INT QUIT

Any CTRL-C, CTRL- or termination of the program that uses the TERM signal will first call cleanup

note:

· The logic of trap can be very tricky (for example, to deal with signal race conditions)

· KILL signal cannot be captured in this way

But in most cases, I will use it in a similar 'cleanup' to achieve the purpose of the function.

8) Shell variable

It is well worth knowing the standard shell variables available. These are my favorite.

RANDOM

Don't rely on this to encrypt the stack, but you can generate random numbers, for example when creating temporary files in scripts:

$ echo $ {RANDOM} 16313 $ # Not enough digits? $ echo $ {RANDOM} $ {RANDOM} 113610703 $ NEWFILE = / tmp / newfile _ $ {RANDOM} $ touch $ NEWFILE

REPLY

No need to give read a variable name

$ readmy input $ echo $ {REPLY}

LINENO and SECONDS

Easy to debug

$ echo $ {LINENO} 115 $ echo $ {SECONDS}; sleep 1; echo $ {SECONDS}; echo $ LINENO174380174381116

Note that even if you use; to separate commands, the above code should be divided into two lines

TMOUT

Can be used for timeout reading, it is really good in some scripts

#! / bin / bashTMOUT = 5echo You have 5 seconds to respond ... readecho $ {REPLY: -noreply}

9) Extglobs

If you are really addicted to bash and cannot extricate yourself, then you may want to enhance your wildcarding capabilities. You can set the extglob option in the shell. This is the setting method:

shopt -s extglobA = "12345678901234567890" B = "$ {A}"

Now let's see if you can point out the functions of the following statements:

echo "B | $ {B} |" echo "B # + () | $ {B # + ()} |" echo "B #? () | $ {B #? ()} |" echo "B # * () | $ {B # * ()} | "echo" B ## + () | $ {B ## + ()} | "echo" B ## * () | $ {B ## * ()} | "echo" B ## ? () | $ {B ##? ()} | "

Although it may be useful, it is difficult to imagine a situation where you must use this method. Usually you will use some tools that are more suitable for the corresponding task (like sed) or just give up bash and use some "appropriate" programming language like python.

10) Associative array

When it comes to porting to other languages, an important rule is that if I need to use arrays, then I will give up bash and use python (for this I even created a Docker Container to run a dedicated tool)

I didn't know it until I read it, there is an associative array in bash

The following is a demonstration:

$ declare -A MYAA = ([one] = 1 [two] = 2 [three] = 3) $ MYAA [one] = "1" $ MYAA [two] = "2" $ echo $ MYAA $ echo $ {MYAA [one]} $ MYAA [one] = "1" $ WANT = two $ echo $ {MYAA [$ WANT]}

Note only for bash 4.x + version

8 Inches Tablet PC

The 8-inch tablet will have a big impact on the 7-inch and 10-inch tablet market. Because the portability of an 8-inch tablet is stronger than that of a 10-inch tablet, and the usable area is larger than that of a 7-inch tablet. The most important thing is that the price is more moderate, which is much cheaper than a 10-inch tablet. It can be said that the 8-inch tablet computer has a good balance between portability and screen display area, and is more likely to be favored by the majority of users.


8 Inches Tablet Pc,Tablet Computer,8 Inch Android Tablets,8 Inch Tablet

Jingjiang Gisen Technology Co.,Ltd , https://www.jsgisentec.com