Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remember which expansion ${var%} ${var#} work from which end? [closed]

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?

like image 521
KamilCuk Avatar asked Mar 01 '21 11:03

KamilCuk


2 Answers

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.

like image 136
Quasímodo Avatar answered Oct 25 '22 04:10

Quasímodo


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 :)

like image 42
RavinderSingh13 Avatar answered Oct 25 '22 03:10

RavinderSingh13