因为括号用于分隔数组,而不是字符串:
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[@]}"
您将字符串构建从 array ids 通过空格的合并转移到 string 类型的新变量。
注意:当"${ids[@]}" 给出一个空格分隔的 字符串时,"${ids[*]}"(用星号* 代替@)将呈现由$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'
字面意思是 space、tabulation 和 (意思是或) 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 将空格作为分隔符。