In bash, how do I join N parameters together as a space separated string
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
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
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# }
}
Check the bash
man page for the entry for '*' under Special Parameters.
join () {
echo "$*"
}