1

I'm trying to join input $* which is one parameter consisting of all the parameters added together.

This works.

#!/bin/bash

foo() {
    params="${*}"
    echo "${params//[[:space:]]/-}"
}

foo 1 2 3 4
1-2-3-4

However, is it possible to skip the assignment of variable?

"${"${*}"//[[:space:]]/-}"

I'm getting bad substitution error.

I can also do

: "${*}"
echo "${_//[[:space:]]/-}"

But it feels hacky.

Filip Seman
  • 1,252
  • 2
  • 15
  • 22

2 Answers2

3

One option could be to set 's internal field separator, IFS, to - locally and just echo "$*":

foo() {
    local IFS=$'-'
    echo "$*"
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

To answer your question, you can do global pattern substitutions on the positional parameters like this:

${*//pat/sub}
${@//pat/sub}

And also arrays like this:

${arr[*]//pat/sub}
${arr[@]//pat/sub}

This won’t join the parameters, but substitute inside them.

Setting IFS to dash adds a dash in between each parameter for echo "$*", or p=$*, but won’t replace anything inside a parameter.

Eg:

$ set -- aa bb 'cc   cc'
$ IFS=-
$ echo "$*"
aa-bb-cc   cc

To remove all whitespace, including inside a parameter, you can combine them:

IFS=-
echo "${*//[[:space:]]/-}"

Or just assign to a name first, like you were doing:

no_spaces=$*
echo "${no_spaces//[[:space:]]/-}"
dan
  • 4,846
  • 6
  • 15