Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Created August 11, 2016 03:26
Show Gist options
  • Select an option

  • Save rcanepa/52961ca56d66146dcc41a7e71bf48af3 to your computer and use it in GitHub Desktop.

Select an option

Save rcanepa/52961ca56d66146dcc41a7e71bf48af3 to your computer and use it in GitHub Desktop.
Piping to bash scripts

Bash accomodates piping and redirection by way of special files. Each process gets it's own set of files (one for STDIN, STDOUT and STDERR respectively) and they are linked when piping or redirection is invoked. Each process gets the following files:

STDIN - /proc//fd/0 STDOUT - /proc//fd/1 STDERR - /proc//fd/2

To make life more convenient the system creates some shortcuts for us:

STDIN - /dev/stdin or /proc/self/fd/0 STDOUT - /dev/stdout or /proc/self/fd/1 STDERR - /dev/stderr or /proc/self/fd/2

#!/bin/bash

echo =================================================
echo Here is the result of looking for pattern $1 
echo =================================================
echo


cat /dev/stdin | grep $1

Usage example:

man ls | ./grep_emulator.sh "[0-9]\{3\}"
=================================================
Here is the result of looking for pattern [0-9]\{3\}
=================================================

             file, in units of 512 bytes, where partial units are rounded up
             size of 512 bytes.
     total number of 512-byte blocks used by the files in the directory is
                      T     The sticky bit is set (mode 1000), but not execute
                      t     The sticky bit is set (mode 1000), and is search-
     files in order to be compatible with the IEEE Std 1003.2 (``POSIX.2'')
     The ls utility conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
BSD                              May 19, 2002                              BSD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment