for循环列出/ etc / passwd文件中的用户

时间:2016-06-21 13:40:07

标签: bash shell

我正在尝试使用for循环从/ etc / passwd文件回显用户,shell和home字段。我正在尝试使用:

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

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

3 个答案:

答案 0 :(得分:1)

传统上readwhile循环配对。直觉上这是有道理的:你通常希望继续阅读,同时有更多的数据需要阅读。这样的循环通常看起来像:

while IFS=: read -r user pass desc home shell; do
    echo "$user has home $home, uses $shell"
done < /etc/passwd

可以尝试将其重写为for in循环,但我不推荐它。

答案 1 :(得分:1)

使用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

...此后:

# the actual for-based iteration, as requested.
# loop over associative array keys, then look up the values
for user in "${!shells[@]}"; do
  echo "Found $user with shell ${shells[$user]}, home ${homes[$user]}"
done

显然,这是一堆额外的工作,如果你有一个令人信服的理由,它只会落入良好实践领域;坚持while read循环通常是最好的做法。

答案 2 :(得分:0)

在这种情况下,您无法使用for循环,因为您不知道您将获得多少输入。 for - 循环是&#34;静态&#34;从某种意义上说,shell需要确切地知道它到达时的迭代内容。

你可以通过实际读取整个文件来绕过这个(并以这种方式逐渐了解要迭代的内容)然后for - 循环遍历该数据,但它会相当笨重。

&#34;正确&#34;方法是read循环中的while

IFS=':'
while read -r user pass uid gid desc home shell; do
  echo "User is '$user', has shell '$shell'"
done </etc/passwd
相关问题