mdsingh
mdsingh

Reputation: 1113

clarification with a shell script

Can somebody explain how echo "${PWD/#$HOME/~}" would print ~ in case the PWD evaluates to $HOME. Never read about such replacement using echo. What is going on here?

Upvotes: 0

Views: 31

Answers (1)

jfs
jfs

Reputation: 414235

It is not echo it is your shell makes Parameter Expansion using ${parameter/pattern/string} syntax:

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. 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. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

It doesn't look like POSIX supports it.

In your case, it replaces the value of $HOME envvar (not the string '$HOME' literally) with ~ in the output if PWD envvar starts with it.

Upvotes: 1

Related Questions