shift
local dst
for s in "$@"
do
if [ "$dst" ]; then
dst=${dst}${sep}${s}
else
dst=${s}
fi
done
echo "$dst"
}
正确:str_join_sep "$SEP" "$ARR[@]"
注意双引号的使用。
[root@jfht ~]# declare -f str_join_sep
str_join_sep ()
{
local sep="$1";
shift;
local dst;
for s in "$@";
do
if [ "$dst" ]; then
dst=${dst}${sep}${s};
else
dst=${s};
fi;
done;
echo "$dst"
}
[root@jfht ~]# ARR=(yes no 'hello world')
[root@jfht ~]# SEP=,
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes,no,hello world
[root@jfht ~]#
实现方式二
{
local sep="$1"
shift
local dst="$1"
shift
for s in "$@"
do
dst=${dst}${sep}${s}
done
echo "$dst"
}
[root@jfht ~]# declare -f str_join_sep
str_join_sep ()
{
local sep="$1";
shift;
local dst="$1";
shift;
for s in "$@";
do
dst=${dst}${sep}${s};
done;
echo "$dst"
}
[root@jfht ~]# ARR=(yes no 'hello world')
[root@jfht ~]# SEP=,
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes,no,hello world
[root@jfht ~]# SEP=:
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes:no:hello world
[root@jfht ~]# SEP='|'
注意加上单引号,否则Bash认为是管道线。
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes|no|hello world
[root@jfht ~]#
作者“Bash @ Linux”