ChiseledAbs
ChiseledAbs

Reputation: 2071

What is ${variable//,/ } in bash?

A script is capturing a serie of comma delimited arguments and I'm wondering how it works. Why are there 3 slashes after cryptoptions inside a subshell call :

for cryptopt in ${cryptoptions//,/ }; do

What is this syntax corresponding to ?

Upvotes: 2

Views: 54

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60097

Try this:

cryptoptions=foo,bar,baz
for cryptopt in ${cryptoptions//,/ }; do
    echo $cryptopt
done

It effectively corresponds to:

for cryptopt in $(echo "$cryptoptions" | sed 's/,/ /g'); do
    echo $cryptopt
done

and utilizes the fact that unquoted variables split on whitespace.

The former is is much faster, because it doesn't spawn processes.

Upvotes: 0

janos
janos

Reputation: 124704

This is not a "sed like variable call in bash", it has nothing to with sed at all.

From man bash, in the Pattern substitution section:

   ${parameter/pattern/string}
          Pattern substitution.  The pattern is expanded to produce a pat-
          tern just as in pathname 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.

In other words:

  • ${cryptoptions/,/ } : replace the first , with a space
  • ${cryptoptions//,/ } : replace every , with a space

And the for cryptopt in words; do ...; done you have around this is a loop. For each word in words, it will execute the loop body, the code between do and done.

Upvotes: 3

Related Questions