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
Author by
user983124
Updated on June 05, 2022Comments
-
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 over 11 yearsJust to clarify, the first character of
$IFS
is used for the separator. -
tripleee over 11 yearsActually the correct solution is
"$@"
if you need to handle quoted arguments. -
tripleee over 11 yearsYou should perhaps declare
local str
andlocal i
just to be on the safe side.for i; do
defaults to processing"$@"
but that's obviously just a shorthand. -
chepner over 11 yearsThe 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 ofjoin
to quote the result, regardless of which parameter is used to access the args. -
tripleee over 11 yearsQuoting can be used to protect other special characters, too, not just single whitespace characters.
-
bsb almost 11 years"join" may intend /usr/bin/join, so "spjoin" might be a safer name
-
jpbochi almost 5 yearsuse
local IFS="$delim"
and you don't need to worry about having to restore it.