Reputation: 347
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()
{
??
}
Upvotes: 15
Views: 12133
Reputation: 98088
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
Upvotes: 9
Reputation: 1937
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
Upvotes: 6
Reputation: 56129
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# }
}
Upvotes: 9
Reputation: 531938
Check the bash
man page for the entry for '*' under Special Parameters.
join () {
echo "$*"
}
Upvotes: 30