Find the answer to your Linux question:
Results 1 to 4 of 4
using bash, if i do this: Code: ps -ef | grep cups | grep -v grep i get some results Code: root 4085 1 0 Aug11 ? 00:00:00 cupsd root ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jan 2009
    Location
    Minneapolis, MN
    Posts
    15

    Unhappy "for" loops and command results


    using bash, if i do this:
    Code:
    ps -ef | grep cups | grep -v grep
    i get some results
    Code:
    root      4085     1  0 Aug11 ?        00:00:00 cupsd
    root     12935     1  0 Jan12 ?        00:00:00 cups-config-daemon
    but i want to manipulate that row by row, but each value in those lines is then read as a new line

    Code:
    for i in `ps -ef | grep cups | grep -v grep`
    do
      echo "This line is: $i"
    done
    
    This line is: root
    This line is: 4085
    This line is: 1
    This line is: 0
    This line is: Aug11
    This line is: ?
    This line is: 00:00:00
    This line is: cupsd
    This line is: root
    This line is: 12935
    This line is: 1
    This line is: 0
    This line is: Jan12
    This line is: ?
    This line is: 00:00:00
    This line is: cups-config-daemon
    instead of

    Code:
    This line is: root      4085     1  0 Aug11 ?        00:00:00 cupsd
    This line is: root     12935     1  0 Jan12 ?        00:00:00 cups-config-daemon
    It behaves the same if i dump the output to a file and then do the for loop on the `cat $FILE`. What am I missing?
    Last edited by glamiss; 08-14-2013 at 07:45 PM. Reason: cleaning

  2. #2
    Just Joined!
    Join Date
    Jan 2009
    Location
    Minneapolis, MN
    Posts
    15
    Also, I want to avoid wc -l'ing the file and then looping through the file with head -1 | tail -$line on each line in the file...

  3. #3
    Linux Newbie
    Join Date
    Nov 2012
    Posts
    224
    hi,

    for loops iterate over words, not lines.

    use a while loop instead.

    what shell are you using?
    bash/ksh:
    Code:
    while read line; do echo "line : $line"; done < <(ps -ef | grep c[u]ps)
    does code has to be portable ?
    sh:
    Code:
    ps -ef | grep c[u]ps | while read line; do echo "line: $line"; done

  4. #4
    Just Joined!
    Join Date
    Jan 2009
    Location
    Minneapolis, MN
    Posts
    15
    Interesting...

    I had started changing my IFS from $' \t\r' to... well, i forget. I'm not at the office anymore. I think i did IFS=' \n'. But the "while read" intrigues me. I'll look more into that. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •