Recently, I was writing shell scripts and found some tricky operations on shell strings, which can improve efficiency.
string read
- ${var} : the value of the variable var
- ${var-DEFAULT} : If var is not declared, the value of var is $DEFAULT
- ${var:-DEFAULT} : If var is not declared, or is empty, the value of var is $DEFAULT
- ${var=DEFAULT} : If var is not declared, the value of var is $DEFAULT
- ${var: =DEFAULT} : If var is not declared, or is empty, the value of var is $DEFAULT
- ${#var} : get the length of $var
String manipulation
- ${#string} : length of $string
- ${string:position} : substring starting at $position
- ${string:position:length} : A substring of length length starting at $position
- ${string#substring} : From the beginning, delete the shortest string matching $substring
- ${string##substring} : from the beginning, delete the longest string matching $substring
- ${string%substring} : From the end, delete the shortest string matching $substring
- ${string%%substring} : From the end, delete the longest string matching $substring
- ${string/str1/str2} : replace the first matching $str1 with str2
- ${string//str1/str2} : replace all matching $str1 with str2
- ${string/#str1/str2} : If the prefix of $string matches $str1, replace $str1 with $str2
- ${string/%str1/str2} : If the suffix of $string matches $str1, replace $str1 with $str2