因为括号用于分隔数组,而不是字符串:
ids="1 2 3 4";echo ${ids// /|}
1|2|3|4
一些示例:填充$ids两个字符串: a b和c d
ids=("a b" "c d")
echo ${ids[*]// /|}
a|b c|d
IFS='|';echo "${ids[*]}";IFS=$' \t\n'
a b|c d
...最后:
IFS='|';echo "${ids[*]// /|}";IFS=$' \t\n'
a|b|c|d
其中数组被组装,由 的第一个字符分隔,但在数组的每个元素$IFS中用空格替换。|
当你这样做时:
id="${ids[@]}"
您将字符串构建从通过空格合并数组的方式转移到 stringids类型的新变量。
注意:当"${ids[@]}"给出一个空格分隔的字符串时,"${ids[*]}"(用星*号代替 at 符号)将呈现一个由 . 的第@一个字符分隔的字符串。$IFS
什么man bash说:
man -Len -Pcol\ -b bash | sed -ne '/^ *IFS /{N;N;p;q}'
IFS The Internal Field Separator that is used for word splitting
after expansion and to split lines into words with the read
builtin command. The default value is ``<space><tab><newline>''.
玩$IFS:
declare -p IFS
declare -- IFS="
"
printf "%q\n" "$IFS"
$' \t\n'
字面意思是 a space, atabulation和(意思是或) a line-feed。所以,虽然第一个字符是一个空格。的使用*将与@.
但是:
{
IFS=: read -a array < <(echo root:x:0:0:root:/root:/bin/bash)
echo 1 "${array[@]}"
echo 2 "${array[*]}"
OIFS="$IFS" IFS=:
echo 3 "${array[@]}"
echo 4 "${array[*]}"
IFS="$OIFS"
}
1 root x 0 0 root /root /bin/bash
2 root x 0 0 root /root /bin/bash
3 root x 0 0 root /root /bin/bash
4 root:x:0:0:root:/root:/bin/bash
注意:该行将IFS=: read -a array < <(...)用作:分隔符,无需$IFS永久设置。这是因为输出行将#2空格作为分隔符。