Bash: Check If Script is Running through Pipe

Bash scripts can be run directly with arguments, or through pipes.

Most unix programs like wc, grep, awk supports pipe mode. Which means, external data is is redirected into the program as stdin.

Here is an example script to test if the script is running through pipe or not.


if read -t 0
    echo "Running in pipe mode"
    echo "Data: $data"
    echo "Running in normal mode"
    echo "Arguments: $@"

Let’s execute it directly.

minhaz@desktop ~> ./test 'Hello World'
Running in normal mode
Arguments: Hello World

And try again using pipe.

minhaz@desktop ~> echo 'Hello World' | ./test
Running in pipe mode
Pipe Data: Hello World

Make sure you run the sript with bash, not sh. Otherwise the following error message may appear.

read: Illegal option -t