I am having trouble remembering which one of the parameter expansions ${var%subst} or ${var#subst} remove from the front and which one from the back of the string. Example:
$ var=/a/b/c
$ echo dirname=${var#/*} filename=${var%%*/}
dirname=a/b/c filename=/a/b/c # Wrong!
$ echo dirname=${var%/*} filename=${var##*/}
dirname=/a/b filename=c
I always mix them and either end up writing some test commands or checking the manual. It's easy to remember that %% removes more then %, because %% is a longer string then %, 2 characters vs 1 character, same for ## vs #. But I always mix % with #.
Is there a memory rule to know which % or # remove from which end of the string?
Percent symbols % always come last in numbers (e.g. 86%), so they remove from the end.
The hash symbols # start comments, so they remove from the start.
Remember only 1 and other will be Opposite of it.
# Shebang starts from a hash which means it will remove from starting till pattern, if you remember this and you know what other does IMHO :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With