Sukarn Nigam Sukarn Nigam - 4 months ago 7x
Bash Question

For loop to list users in /etc/passwd file

I am trying to echo user, shell and home fields from /etc/passwd file using a for loop. What I am trying is to use:

IFS Separator

read -r user pass desc home shell
for storing fields in these variable then print them.

I can use while loop instead, but I would like to use FOR loop. Any help would be appreciated.


In this case you can't use a for-loop as you don't know how much input you will get. A for-loop is "static" in the sense that the shell needs to know exactly what it's iterating over when it gets to it.

You could bypass this through actually reading in the whole file (and in that way get to know exactly what to iterate over) and then for-looping over that data, but it would be rather clunky.

The "correct" way is to read in a while-loop:

while read -r user pass uid gid desc home shell; do
  echo "User is '$user', has shell '$shell'"
done </etc/passwd