Pipes, and how using them in bash

6,049

The pipe connects stdout of one program to stdin of another, so in your script simply read from stdin and you will get what the previous command printed out. A simple way to read this into a variable is with cat for example inside myprogram.sh:

mypipevar="$(cat ${1:-/dev/stdin})"
echo "Obtained the value: '$mypipevar'"

However, quite often you want to process things line by line rather then all at once, this can be done with

while read line
do
  echo "$line"
done < "${1:-/dev/stdin}"

Note that ${1:-/dev/stdin} will give you the first argument, or if no arguments are specified then /dev/stdin which will contain the contents of stdin which can be read like a file. This allows you to execute the script as either command | script or simply as script filename.

Share:
6,049

Related videos on Youtube

paulj
Author by

paulj

Updated on September 18, 2022

Comments

  • paulj
    paulj over 1 year

    I see commands like this in some scripts: /bin/cat somefile | someprogram. I would like to know how to read the entire pipe the same way someprogram does. So when I run /bin/cat something | myprogram.sh, myprogram.sh has a variable called mypipevar equal to whatever was piped - all of the pipe text. If this is unclear, please let me know. I have read that read will likely not work, and bash may not be the right shell.