Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    BASH: how to read from piped stdout


    Hi,

    I'd like to read some output from a console app, prepend some text and write the modified text to stdout. CTRL-C can be used to stop the operation. So suppose I have a text file (e.g. a README) like this:

    Code:
    Here is
    some text
    I want to be able to type this:

    Code:
    cat README | ./prepend-with-foo
    to get this:

    Code:
    FOO: Here is
    FOO: some text
    I've tried the following script but "cat ./README | ./prepend-with-foo" doesn't work; it writes many lines of "FOO:" but nothing else. Any ideas?

    Code:
    #!/bin/bash
    while [ 1 ]; do
      read FROM_STDIN
      echo "FOO: $FROM_STDIN"
    done

  2. #2
    Your script actually does output your STDIN but it's too fast that you could notice that. You have to exit the loop as soon as no line is left:
    Code:
    while [ 1 ]; do
            read FROM_STDIN
            if [[ ! -n $FROM_STDIN ]]; then
                    break
            fi 
            echo "FOO: ${FROM_STDIN}"
    done
    But
    Code:
    cat README | ./prepend-with-foo
    is a candidate for the Useless Use of Cat Award.
    Just use
    Code:
    ./prepend-with-foo < ./README
    But I wonder why you write your own script instead of using some tool like sed.

  3. #3
    Code:
    sed  -e 's/^/FOO /g' ./README

  4. $spacer_open
    $spacer_close

Posting Permissions

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