Read stdin OR a file passed as argument in bash

Created: — modified: — tags: bash

TL;DR: cat "${1:-/dev/stdin}"

Many *nix utilities (cat, grep, head, tail, sed,...) have a nice feature: they can either process stdin, or a file passed as argument. For example:

# first lines of a file
head file.txt
# first lines of a command's output
ls | head

Turns out, it's pretty easy to add the same feature to your bash script(s)!

Just assign filename to a variable, with /dev/stdin as default value.

For example:

#!/usr/bin/env bash

# unlc - print number of unique lines in the optional input file or stdin
#
# Usage:
#
#   unlc [input-file]

input_file="${1:-/dev/stdin}"

cat "$input_file" | sort | uniq | wc -l

Naturally, you're not limited by using only the first argument, you can combine it with argument processing tricks, but this is left as excersise for the reader ;-)

Source: How to make Bash scripts read from stdin by Paolo Amoroso, originally taken from this StackExchange answer by user Daniel.