Shell script ${}, ## and %% usage example

file=/dir1/dir2/dir3/my.file.txt


You can replace them with ${ } to get different values:

${file#*/}: delete the first / and the string to its left: dir1/dir2/dir3/my.file.txt
${file##*/}: delete the last / and its left String: my.file.txt
${file#*.}: delete the first . and its left string: file.txt
${file##*.}: delete the last . and its left String: txt
${file%/*}: delete the last / and its right string: /dir1/dir2/dir3
${file%%/*}: delete the first / and its right String: (null)
${file%.*}: delete the last . and the string to the right of it: /dir1/dir2/dir3/my.file
${file%%.*}: delete the first . and the string to the right of it: /dir1/dir2/dir3/my


The way to remember is:

# is to remove the left (# is on the left of $ on the keyboard)
% is to remove the right (% is on the right of $ on the keyboard) A
single symbol is the smallest match; two symbols are the largest match
${file:0:5}: extract the leftmost 5 bytes of: /dir1
${file:5:5}: Extract 5 consecutive bytes to the right of the 5th byte: /dir2


You can also replace strings in variable values:

${file/dir/path}: Replace the first dir with path: /path1/dir2/dir3/my.file.txt
${file//dir/path}: Replace all dirs with path: /path1/ path2/path3/my.file.txt


Using ${ } can also assign values ​​to different variable states (unset, null, non-null):

${file-my.file.txt} : If $file is not set, use my.file.txt as the return value. (null and non-null values ​​are not processed)
${file:-my.file.txt} : If $file is not set or is null, use my.file.txt as the return value. (No processing if non-null)
${file+my.file.txt} : If $file is set to null or non-null, use my.file.txt as the return value. (No processing if not set)
${file:+my.file.txt} : If $file is non-null, use my.file.txt as the return value. (No processing if not set and empty)
${file=my.file.txt} : If $file is not set, use my.file.txt as the return value, and assign $file to my.file.txt . (null and non-null values ​​are not processed)
${file:=my.file.txt} : If $file is not set or is null, use my.file.txt as the return value, and assign $file for my.file.txt. (No processing if non-null)
${file?my.file.txt} : If $file is not set, output my.file.txt to STDERR. (null and non-null values ​​are not processed)

${file:?my.file.txt} : If $file is not set or is empty, output my.file.txt to STDERR. (No processing for non-null values)
${#var} can calculate the length of the variable value:

${#file} gets 27, because /dir1/dir2/dir3/my.file.txt is 27 bytes
[/code]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324587133&siteId=291194637