by croo · 7y ago · 0 comments
trim_string() {
# Usage: trim_string " example string "
: "${1#"${1%%[![:space:]]*}"}"
: "${_%"${_##*[![:space:]]}"}"
printf '%s\n' "$_"
}
Ok, so the : is somehow a temporary variable...
Then there is a variable starting at $ and you lost me :D
Can someone break down that line for me? What the hell is going on here? : "${1#"${1%%[![:space:]]*}"}"Because $_ is used in the expansion of itself, it is the same value, because the command has not yet completed, which would (re) set $_. So use of a thing ($_) in expanding the same thing ($_) is perfectly fine until after that (null) command (:) runs. You see that the final $_ is used standalone. Hope this helps.
: "${1#"${1%%[![:space:]]*}"}"
The $_ temporary variable contains the result of removing the leading spaces. In the next line, the spaces at the end are removed from the temporary variable with the "${_%..." syntax.You can test this in your own shell by e.g. doing:
: $PATH
echo $_: is a "do nothing" command -- but the line is still evaluated
%% means to replace leading chars that match pattern
## means replace trailing chars
I don't know why they're using $_; thats the variable containing the interpreter name, i.e. "/bin/bash" [edit - also the name of the previous command!]
I can't be bothered analyzing it any further :-)