2

How do I pass the $line to the cut command properly in this loop?

while read line
do
    login= $(cut -d : -f 1)

done < /etc/passwd

I can't do $(cut -d : -f 1 $line) so what is the correct way?

Oliver Salzburg
  • 86,445
  • 63
  • 260
  • 306
Mike
  • 1,427
  • 3
  • 11
  • 8

3 Answers3

3

Let the read command together with the shell IFS variable parse the line for you:

while IFS=: read -r login restOfLine; do
    doSomethingWith $login
done < /etc/passwd

To answer your question, the bash here-string would be useful:

login=$(cut -d: -f1 <<< "$line")
glenn jackman
  • 25,463
  • 6
  • 46
  • 69
2

Use echo:

login=$(echo "$line" | cut -d : -f 1)
Dennis
  • 48,917
  • 12
  • 130
  • 149
1

You don't actually need the while loop if your intention is only to list the names. Also there is a syntax error after login=, there should be no space.

cut -d: -f1 /etc/passwd | \
while read login; 
do 
    echo username: $login;
done

or as you tried:

while read line; do
   login=$(echo $line | cut -d : -f 1)
   echo $login
done < /etc/passwd

even better:

db-getent passwd |cut -d: -f1 | xargs -L1 echo name:
  • 1
    +1 for `getent`. In your first example, line continuations are not required after a pipe. – glenn jackman Mar 11 '13 at 01:14
  • Perfect! Thanks Ярослав, the loop was a snippet of code from a larger while loop so your second suggestion is perfect for me. – Mike Mar 11 '13 at 17:54