sh shell:如何在数组中获取和存储可能包含 space 的值

sh shell: how do I grab and store values, which may have space, in an array

我正在尝试编写脚本以从 passwd 文件

中获取用户
USERS_LIST=( $( cat /etc/passwd | cut -d":" -f1 ) )

到目前为止,上面的方法可以解决问题,因为我只有名字中没有 space 的用户。

然而,现在已经不是这样了。我需要能够解析名称中很可能包含 space 的用户名。

我尝试逐行读取文件,但存在同样的问题(这是一行,但为了清楚起见,我在这里缩进了它):

tk=($( while read line ; do 
       j=$(echo ${line} | cut -d":" -f1 ) 
       echo "$j" 
       done < /etc/passwd )
   )

不幸的是,如果我尝试打印数组,带有 space 的用户名将被分成 2 个数组单元格。 所以用户名 "named user" ,将占据数组 [0] 和 [1] 位置。

如何在 sh shell 中解决这个问题?

感谢您的帮助!

数组 bash(以及 ksh 和 zsh)特性在 POSIX sh 中不存在,因此我假设您是想询问 bash。你不能在 sh 的数组中存储任何东西,因为 sh 没有数组。


不要那样填充数组。

users_list=( $( cat /etc/passwd | cut -d":" -f1 ) )

...字符串拆分和全局扩展内容。相反:

# This requires bash 4.0 or later
mapfile -t users_list < <(cut -d: -f1 </etc/passwd)

...或...

IFS=$'\n' read -r -d '' -a users_list < <(cut -d: -f1 </etc/passwd)

现在,如果您真的想要POSIX sh 兼容性,一个数组——正好一个,参数列表。如果您认为合适,可以覆盖它。

set --
cut -d: -f1 </etc/passwd >tempfile
while read -r username; do
  set -- "$@" "$username"
done <tempfile

此时,"$@" 是一个用户名数组。