Bash

在 ZSH 中按空格分割字元串

  • February 14, 2019

給這個file.txt

first line
second line
third line

這適用於bash

while IFS=' ' read -a args; do
 echo "${args[0]}"
done < file.txt

生產

first
second
third

也就是說,我們能夠逐行讀取文件,並且在每一行上,我們將行進一步拆分為一個使用空格作為分隔符的數組。但在 中zsh,結果是一個錯誤:read: bad option: -a

我們如何才能實現與 inzsh相同的目標bash?我嘗試了幾種解決方案,但我永遠無法使用空格作為分隔符將字元串拆分為數組

man zshbuiltins,zsh 的 read 改為使用-A

read [ -rszpqAclneE ] [ -t [ num ] ] [ -k [ num ] ] [ -d delim ]
    [ -u n ] [ name[?prompt] ] [ name ...  ]
...
      -A     The  first  name  is taken as the name of an array
             and all words are assigned to it.

因此命令是

while IFS=' ' read -A args; do
 echo "${args[1]}"
done < file.txt

注意預設情況下,zsh 數組編號以 開頭1,而 bash 以 . 開頭0

$ man zshparam
...
Array Subscripts
...
The elements are numbered  beginning  with  1, unless the
KSH_ARRAYS option is set in which case they are numbered from zero.

引用自:https://unix.stackexchange.com/questions/500537