The usage of shell's ${}

The following content is basically extracted from the Shell13 question.
1. Truncation function
${file#*/}: remove the first / and its left string: dir1/dir2/dir3/my.file.txt
${file# #*/}: remove the last / and the string to the left: my.file.txt
${file#*.}: remove the first. and the string to the left: file.txt
${file# #*.}: remove the last . and its left string: txt
${file%/*}: remove the last / and its right string: /dir1/dir2/dir3
${file%%/ *}: remove the first / and the string to the right: (null)
${file%.*}: remove the last. and the string to the right: /dir1/dir2/dir3/my.file
${file%%.*}: Remove the first . and the string to the right: /dir1/dir2/dir3/my
The method of memory is:
[list]# is to remove the left ,  ##The last
      % is to remove On the right,  %% first
2. String extraction 
of a single symbol is the smallest match; two symbols is the largest match.
${file:0:5}: Extract the leftmost 5 bytes: /dir1
${file:5:5}: Extract the 5 consecutive bytes to the right of the 5th byte: /dir2
3. String replacement
${file/dir/path}: extract the first dir to path: /path1/dir2/dir3/my.file.txt
${file//dir/path}: extract all dirs to path:/ path1/path2/path3/my.file.txt
4. Assign values ​​to different variable states (unset, null, non-null):
${file-my.file.txt}: If $file is not set, Then 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 a non-null value, 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. (It will not be processed when it is not a null value)
Note: 
The case of ":+" does not contain a null value.
":-", ":=", etc. as long as there is a sign, it contains a null value (null).

5. The length of the variable
$ {#file}
6. Array operation
A=(abc def)
${A[@]} or ${A[*]} can get abc def (all groups)
${A[0]} can get a (th one group), ${A[1]} is the second group...
${#A[@]} or ${#A[*]} gives 4 (the full number of groups)
$ {#A[0]} gets 1 (the length of the first group (a)), ${#A[3]} gets 3 (the length of the fourth group (def))

Guess you like

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