5

I saw the following substitution in this article:

${PWD/#$HOME/~}

How does it compare to this?

${PWD/$HOME/~}

Both seem to be the same. I don't know why the hash was included.

2 Answers 2

7

man bash, explanation for ${parameter/pattern/string}:

If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter.

> var=abcd
> echo "${var/bc/_}"
a_d
> echo "${var/#bc/_}"
abcd
3

Speaking about pattern matching and substitution in short for the ${parameter/pattern/string} format with some examples:

If the pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced.

> test=test
> echo ${test//t/-} 
> -es-

If pattern begins with #, it must match at the beginning of the expanded value of parameter.

> test=test
> echo ${test/#t/-}
> -est

If pattern begins with %, it must match at the end of the expanded value of parameter.

> test=test
> echo ${test/%t/-}
> tes-

An example with using asterix *:

> test=test
> echo ${test/#*es/-}
> -t

Reference: man bash: ${parameter/pattern/string}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.