Bash For循环在/etc/passwd文件中列出用户

Bash For循环在/etc/passwd文件中列出用户,bash,shell,Bash,Shell,我试图使用for循环从/etc/passwd文件回显user、shell和home字段。我尝试的是使用: IFS=:IFS分隔符 read-r user pass desc home shell用于存储这些变量中的字段,然后打印它们 我可以使用while循环,但是我想使用FOR循环。任何帮助都将不胜感激 传统上reads与配对,而循环。直观地说,这是有道理的:您通常希望在有更多数据需要读取时继续读取。这样的循环通常看起来像: while IFS=: read -r user pass desc

我试图使用for循环从/etc/passwd文件回显user、shell和home字段。我尝试的是使用:

IFS=:
IFS分隔符
read-r user pass desc home shell
用于存储这些变量中的字段,然后打印它们


我可以使用while循环,但是我想使用FOR循环。任何帮助都将不胜感激

传统上
read
s与
配对,而
循环。直观地说,这是有道理的:您通常希望在有更多数据需要读取时继续读取。这样的循环通常看起来像:

while IFS=: read -r user pass desc home shell; do
    echo "$user has home $home, uses $shell"
done < /etc/passwd
而IFS=:read-r user pass desc home shell;做
echo“$用户有家$home,使用$shell”
完成

您可以尝试将其重写为for-in循环,但我不建议这样做。

对于bash 4.0或更高版本,您可以将这些项存储在关联数组中,并使用
for
循环迭代该数组

# prep work: storing in an associative array per field
declare -A homes=( ) shells=( )
while IFS=: read -r user _ _ home shell _; do
  [[ $user = "#"* || ! $user ]] && continue # skip comments, empty lines
  homes[$user]=$home
  shells[$user]=$shell
done </etc/passwd # or < <(getent passwd), to work on LDAP or NIS systems as well
显然,这是一堆额外的工作,只有在你有令人信服的理由的情况下,它才会属于良好实践领域;阅读时坚持
循环通常是最佳做法。

在这种情况下,您不能将
用于
循环,因为您不知道将获得多少输入。
-for的
循环是“静态”的,因为shell需要确切地知道它到达它时迭代的内容

您可以通过实际读取整个文件(这样就可以确切地知道要迭代什么),然后对该数据进行
循环,从而绕过此问题,但这将相当麻烦

“正确”的方法是在
循环中
读取
,而
循环:

IFS=':'
while read -r user pass uid gid desc home shell; do
  echo "User is '$user', has shell '$shell'"
done </etc/passwd
IFS=':'
当read-r用户传递uid gid desc home shell时;做
echo“用户为'$User',具有shell'$shell'”

完成你很可能会因为没有表现出任何开始、努力或遇到的问题而被否决。为什么要使用“for”循环,在我看来有更好的方法。你应该分享你的目标。如果你只想打印用户、shell和home字段(按此顺序)而不打印其他内容,为什么不直接执行:
awk-F':“{print”用户:“$1”shell:$7”home:$6}'/etc/passwd
?不,在这种情况下,你必须使用
while
循环。
for
循环要求您知道所迭代的内容。这是完全正确的,但我从问题中得到的明显印象是,OP已经知道了很多,并且出于一些难以理解的原因,我打算做其他事情。明白了,我知道我可以使用while循环来完成,但是我想进行测试谢谢大家的建议。
IFS=':'
while read -r user pass uid gid desc home shell; do
  echo "User is '$user', has shell '$shell'"
done </etc/passwd