In bash, how do I join N parameters together as a space separated string

11,557

Solution 1

Check the bash man page for the entry for '*' under Special Parameters.

join () {
    echo "$*"
}

Solution 2

For the immediate question, chepner's answer ("$*") is easiest, but as an example of how to do it accessing each argument in turn:

func(){
    str=
    for i in "$@"; do 
        str="$str $i"
    done
    echo ${str# }
}

Solution 3

This one behaves like Perl join:

#!/bin/bash

sticker() {
  delim=$1      # join delimiter
  shift
  oldIFS=$IFS   # save IFS, the field separator
  IFS=$delim
  result="$*"
  IFS=$oldIFS   # restore IFS
  echo $result
}

sticker , a b c d efg 

The above outputs:

a,b,c,d,efg

Solution 4

Similar to perreal's answer, but with a subshell:

function strjoin () (IFS=$1; shift; echo "$*");
strjoin : 1 '2 3' 4
1:2 3:4

Perl's join can separate with more than one character and is quick enough to use from bash (directly or with an alias or function wrapper)

perl -E 'say join(shift, @ARGV)'  ', '   1 '2 3' 4
1, 2 3, 4
Share:
11,557
user983124
Author by

user983124

Updated on June 05, 2022

Comments

  • user983124
    user983124 almost 2 years

    I'm trying to write a function that takes n parameters and joins them into a string.

    In Perl it would be

    my $string = join(' ', @ARGV);
    

    but in bash I don't know how to do it

    function()
    {
        ??
    }
    
  • cdarke
    cdarke over 11 years
    Just to clarify, the first character of $IFS is used for the separator.
  • tripleee
    tripleee over 11 years
    Actually the correct solution is "$@" if you need to handle quoted arguments.
  • tripleee
    tripleee over 11 years
    You should perhaps declare local str and local i just to be on the safe side. for i; do defaults to processing "$@" but that's obviously just a shorthand.
  • chepner
    chepner over 11 years
    The goal here is to collapse all the arguments into a single string, so the choice of $* or $@ doesn't matter. Or rather, it's up to the consumer of join to quote the result, regardless of which parameter is used to access the args.
  • tripleee
    tripleee over 11 years
    Quoting can be used to protect other special characters, too, not just single whitespace characters.
  • bsb
    bsb almost 11 years
    "join" may intend /usr/bin/join, so "spjoin" might be a safer name
  • jpbochi
    jpbochi almost 5 years
    use local IFS="$delim" and you don't need to worry about having to restore it.