1

In bash, how to join arguments of a function into a single string?

The seperator is fixed, and is not space (thus "$*" is not what I want). Here use ", " as example.

join_args() {
# join args with sep ", ", then echo the joined string
# ... code here
}

join_args abc def ghi
# abc, def, ghi
codeforester
  • 39,467
  • 16
  • 112
  • 140
qeatzy
  • 1,363
  • 14
  • 21

3 Answers3

2

$* can work with characters other than space if you set $IFS, but it can only use one character. Thus

join_args() {
    local IFS=', '
    echo "${*}"
}

outputs abc,def,ghi.

If you need longer separators, you have to use a loop:

join_args() {
    while (($# > 1)) ; do
        printf '%s, ' "$1"
        shift
    done
    if (($#)) ; then
        printf '%s\n' "$1"
    fi
}

Or, use a real programming language:

perl -E 'say join ", ", @ARGV' abc def ghi
choroba
  • 231,213
  • 25
  • 204
  • 289
1

You can try:

$ function join_by { local IFS="$1"; shift; echo "$*"; }

Then use by:

$ join_by , abc def ghi
abc,def,ghi

If you want the extra space after the ", ", use sed I suppose:

$ join_by , abc def ghi | sed -e 's/,/, /g'
abc, def, ghi

Or you can use printf with parameter expansion thus:

$ function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }
$ arr=( abc def ghi "kl mn op" )
$ echo $(join_by ", " "${arr[@]}")
abc, def, ghi, kl mn op
dawg
  • 98,345
  • 23
  • 131
  • 206
0
#!/usr/bin/env bash

join_args() {
  count=$#
  for i in `seq 1 $count`
  do
   if [[ $i = $count ]]
   then
     joined+=("$1")
   else
    joined+=("$1,")
    shift
   fi
  done
echo ${joined[*]}
}

join_args abc def ghi sfl ugw pwg afm

Output:

abc, def, ghi, sfl, ugw, pwg, afm
Konstantin Vustin
  • 6,521
  • 2
  • 16
  • 32