Bash: Check If Script is Running through Pipe
09 Jan 2015 linux
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.
#!/bin/bash
if read -t 0
then
echo "Running in pipe mode"
data=$(cat)
echo "Data: $data"
else
echo "Running in normal mode"
echo "Arguments: $@"
fi
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