I have written a script that will only ever run in a linux environment. The purpose of the script is to be piped to, look for certain strings and modify or not and send to STDOUT or not similar to grep/awk/sed but with a more specific purpose that those don't address easily.

I have looked though other posts, but didn't find anything. Not sure if that's because it's impossible, everyone else already knows but me or I just don't know how to search.

I'm trying to determine within the script the context in which it is being executed, and/or better yet, the process/command I'm receiving STDIN from. With my current script, if it runs as in the first example below, it just sits waiting for STDIN and won't exit without CTRL-C or some other non-graceful intervention. When it's receiving STDIN as in the second example, everything works as expected.

For Example:
  • [root@server ~]# script
  • or
  • [root@server ~]# cat myfile | script
  • This is an example of the script logic I'm trying to accomplish:

    #!/usr/bin/perl use strict; my @output; my $stuff; if ( <not piped to> and @ARGV == 0 ) { print "This is how you use this perl script...\n"; exit; } while (<STDIN>) { if ($_ =~ m/start/ ) { push @output, chomp; $stuff = 1; } elsif ( $_ =~ m/end/ ) { push @output, chomp; changout(@output); undef $stuff; } elsif ($stuff) { push @output, chomp; } else { print STDOUT $_; } } sub changout { foreach my $line (@_) { if ( $line =~ m/something/ ) { print STDOUT $line; } else { print STDOUT $line."\n"; } } }

    In reply to How do I Determine if my script is being piped to? by netguy

    Title:
    Use:  <p> text here (a paragraph) </p>
    and:  <code> code here </code>
    to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.