# REVISION: 2017-03-14
# Use of read and other bash specific features (bashisms)
因爲括號用於分隔一個陣列,而不是一個字符串:
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[@]}"
你傳遞字符串從陣列ids
的合併建立一個空間字符串類型的新變量。
注:時"${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
播放:
set | grep ^IFS=
IFS=$' \t\n'
declare -p IFS
declare -- IFS="
"
printf "%q\n" "$IFS"
$' \t\n'
字面意思是space
,tabulation
和(意思是或) a line-feed
。所以,第一個角色是空間。使用*
將和@
一樣。
但:
{
# OIFS="$IFS"
# IFS=$': \t\n'
# unset array
# declare -a array=($(echo root:x:0:0:root:/root:/bin/bash))
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
將空格顯示爲分隔符。
'$ {$ {IDS [*]} ///|}'是一個語法錯誤,這是所有。不知道你想在這裏實現什麼。 –
試圖在1跳中實現變量替換,它永遠不會工作... – koola