Make Shellscript act as pipLine

Asked

Viewed 26 times

0

How can I get my script to act in a pipeline

example:

ls|./meuScript|grep 'Mensagem Qualquer'

what './meuScript' has to have to act as a filter ?

1 answer

1


Just have your script use commands that read the default input and write to the default output.

Example:

We have the script abc-lines.sh:

#!/bin/bash
grep abc | wc -l

We can use it in this command:

$ echo -e 'abcd\nefgh\n123abc\nxabcy\nzzz' | \
./abc-lines.sh | \
sed -r 's/(.*)/[\1]/'

...and the result will be: [3]

This is because the default input of your script commands will be the default input of your script (unless the command is after a pipe, such as wc example). The same goes for functions.

If you need to capture the standard input for more elaborate manipulations you can use the read. Example:

#!/bin/bash
while read LINE
do
    echo "I read $LINE"
    # alguma mágica aqui
done

Anything you print, be with echo or any other command, may be used by another script in the sequence of user-made Pipes.

Warning: There are two STDOUT and STDERR outputs. The pipe will transmit to STDOUT.

If you want to send the output of a command to STDERR to escape the PIPE, do:

echo "mensagem de erro" >&2

If you want to merge STDERR with STDOUT to pipette both of you, do:

ls /nowhere 2>&1 | grep something
  • was getting beat up on account of not knowing the detail of read LINE thank you very much.

  • however when I put read LINE and will use the program outside a pipe it hangs

  • It is not locked, is expecting input. It will read what you type. ;-)

  • 1

    That’s exactly what I meant, ( the lock was in the sense of stopping processing and waiting for user input) , I solved this problem by checking the descriptors files if [ -t 0 ]; then ... that checks if the file associated with the file descriptor ends in the terminal window.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.