User Tools

Site Tools


bash-stdin-or-filename

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
bash-stdin-or-filename [2024/02/01 23:30] dblumebash-stdin-or-filename [2024/02/19 14:31] (current) – Moving because now have stdin and stdout sections dblume
Line 1: Line 1:
-====== Bash Script Stdin or Filename ====== 
  
-If you write a shell script and want it to run with either stdin or a filename, like so: 
- 
-    cat file.txt | script.sh 
-    script.sh file.txt 
- 
-There are some options. Here we'll use ''awk'' as the command inside the script. 
- 
-=== The General, Idiomatic Way === 
- 
-The canonical way is to cat the args to the script. 
- 
-<file bash script.sh> 
-#!/usr/bin/env sh 
-cat "$@" | awk -F, '...' 
-</file> 
- 
-=== Shell Default Parameter Substitution === 
- 
-Use Bash parameter substitution to try to pass in ''$1'', but if it doesn't exist, pass in ''/dev/stdin''. 
- 
-<file bash script.sh> 
-#!/usr/bin/env sh 
-awk -F, '...' "${1:-/dev/stdin}" 
-</file> 
- 
-=== Let the Command Handle It === 
- 
-Since we're using ''awk'' as our example, and it already supports stdin or filenames, don't be a 
-bash script, be an awk script. (But in this case we can't use ''/usr/bin/env''.) 
- 
-<file bash script.awk> 
-#!/bin/awk -f 
-BEGIN{FS=","} ... 
-</file> 
bash-stdin-or-filename.1706859040.txt.gz · Last modified: 2024/02/01 23:30 by dblume