Shell Knowledge Reminder

${max:-0} in the shell means that if the max value is empty, the value is 0

The following is some knowledge of the shell about {} expressions

Suppose we define a variable as:
file=/dir1/dir2/dir3/my.file.txt
we can use Respectively replace to obtain different values : {file#*/}: Remove the first / and the string to its left: dir1/dir2/dir3/my.file.txt
{file##*/}: Remove the last / and the string to its left: my.file.txt{file#*.}: remove the first . and the string on its left: file.txt
{file##*.}: Remove the last . and the string to its left: txt{file%/*}: Remove the last / and the string on the right: /dir1/dir2/dir3
{file%%/*}: Remove the first / and the string on its right: (null value){file%.*}: remove the last . and the string on its right: /dir1/dir2/dir3/my.file
${file%%.*}: remove the first . and the string on its right :/dir1/dir2/dir3/my
The memory method is:

It is to remove the left side (# on the left side of $ on the disk)

% is to remove the right side (% is on the right side of $ on the disk).
A single symbol is a minimum match; two symbols are a maximum match.

fi l e : 0 : 5 : extract the leftmost 5 bytes : / d _ _i r 1 {file:5:5}: Extract 5 consecutive bytes to the right of the 5th byte: /dir2

We can also replace strings in variable values:
fi the e / di r / p a t h : convert the first dReplace i r with p a t h : / p a t h 1 / d _i r 2 / dir3/my.file.txt {file//dir/path}: Replace all dir with path: /path1/path2/path3/my.file.txt

use You can also assign values ​​for different variable states ( not set , empty , non - empty ) : {file-my.file.txt} : if fi l e is empty , then use m y _.fi l e . t x t is the default value . ( Reserve not set and non- null value ) {file:-my.file.txt} : if fi l e is not set or is empty , then use m y.fi l e . t x t is the default value . ( preserve non- null value ) {file+my.file.txt} : whatever fWhat is the value of i l e , use m y.fi l e . t x t is the default value . ( no value retained ) _ {file:+my.file.txt} : unless fi l e is null , otherwise use m y _.fi l e . t x t is the default value . ( leave empty ) _ {file=my.file.txt} :若 fIf i l e is not set , use m y.fi l e . t x t as the default value , and set file is defined as a non-null value. (reserve null and non-null values)
file:=my.fi l e . t x t : if If file is not set or is empty, use my.file.txt as the default value, and set fi l e is defined as a non- null value . ( preserve non- null value ) {file?my.file.txt} :若 fIf i l e is not set , set m y.fi l e . t x t output to STD ER R . ( retain null and non - null values ) ) {file:?my.file.txt} : If $file is not set or is empty, output my.file.txt to STDERR. (preserve non-null value)

besides,{#var} calculates the length of the variable value:{#file} gets 27 because /dir1/dir2/dir3/my.file.txt is exactly 27 bytes...

Guess you like

Origin blog.csdn.net/dtwangquan/article/details/47311933