Skip to content

Instantly share code, notes, and snippets.

@mfaani
Last active September 16, 2022 18:20
Show Gist options
  • Save mfaani/a917951d04adb037ed2281bcf8be0e6d to your computer and use it in GitHub Desktop.
Save mfaani/a917951d04adb037ed2281bcf8be0e6d to your computer and use it in GitHub Desktop.
stdin vs stdout

Great video on stdin vs stdout: https://www.youtube.com/watch?v=OsErpB0-mWY

stdin

As a standard your input usually comes from the keyboard. Ex cat file.txt. <- here you're passing file.txt as a parameter.

However you can do cat < $file_name i.e. make the input to the cat command a variable.

Both cat file.txt & cat < file.txt achieve the same, but through different mechanics. < is passing something as an input.

I suppose it's because the cat command has abilities to handle file names as arguments and through stdin

stdout

Similarly the standard output of your cat command is the console. However you can redirect that output to another file using >. Ex echo "hello people" > ppl.txt.

The difference between >> and > is that:

  • >> will append to the file.
  • > will replace everything in the file.

How to make your command accept stdin?

Use /dev/stdin/ Example:

reader.sh

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

Usage:

sh reader.sh file.txt
sh reader.sh < file.txt

If you're wondering about ${1:-<sth>}

It's a form of defaulting / fallback recovery. From here

echo ${parameter:-33} 
# echos 33; because parameter is unset/undefined
parameter=55
echo ${parameter:-33} 
# echos 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment