Why Sponsor Oils? | blog | oilshell.org

Four Slashes and Three Meanings

2016-10-29

Aboriginal Linux has these lines of code:

if [ "$(noversion "${i/*\//}")" == "$1" ]
NO_CLEANUP=${NO_CLEANUP/temp//} blank_tempdir "$WORK"

Note that there are three slashes on each line, which means the last slash is a literal slash, not an operator.

The author is using the pattern replacement operator /, which works like this:

$ foo='-z-z-z'
> echo ${foo/z/ZZ}
-ZZ-z-z

A third meaning for / is as pattern prefix. /z means "replace all occurences of z, not just the first one":

$ foo='-z-z-z'
> echo ${foo//z/ZZ}
-ZZ-ZZ-ZZ

(In addition to /, you can also use # or % for a prefix- or suffix- anchored replacement.)

Now we have our example with four slashes and three meanings for /: operator, literal, and pattern modifier.

$ foo='-z-z-z'
> echo ${foo//z//}
-/-/-/

In the last post I showed five meanings for #, and discussed the larger motivation for this trivia. I will have a few more head-scratchers, and then there should be more "fun" posts.