bash-script-stdio
no way to compare when less than two revisions
Differences
This shows you the differences between two versions of the page.
— | bash-script-stdio [2024/02/19 14:29] (current) – created dblume | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Bash Script Stdin and Stdout ====== | ||
+ | |||
+ | ===== Reading from 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 '' | ||
+ | |||
+ | === The General, Idiomatic Way === | ||
+ | |||
+ | The canonical way is to cat the args to the script. | ||
+ | |||
+ | <file bash script.sh> | ||
+ | # | ||
+ | cat " | ||
+ | </ | ||
+ | |||
+ | === Shell Default Parameter Substitution === | ||
+ | |||
+ | Use Bash parameter substitution to try to pass in '' | ||
+ | |||
+ | <file bash script.sh> | ||
+ | # | ||
+ | awk -F, ' | ||
+ | </ | ||
+ | |||
+ | === Let the Command Handle It === | ||
+ | |||
+ | Since we're using '' | ||
+ | bash script, be an awk script. (But in this case we can't use ''/ | ||
+ | |||
+ | <file bash script.awk> | ||
+ | #!/bin/awk -f | ||
+ | BEGIN{FS="," | ||
+ | </ | ||
+ | |||
+ | ===== Writing to Stdout and/or to file ===== | ||
+ | |||
+ | To just append script output to the file | ||
+ | |||
+ | <file bash script.sh> | ||
+ | # | ||
+ | set -euf -o pipefail | ||
+ | |||
+ | # Just append stdout to the file | ||
+ | exec >> | ||
+ | |||
+ | # (now the rest of your script) | ||
+ | </ | ||
+ | |||
+ | Or write output to stdout and append the same output to the file. | ||
+ | |||
+ | <file bash script.sh> | ||
+ | # | ||
+ | set -euf -o pipefail | ||
+ | |||
+ | # Write to stdout and append to the file | ||
+ | exec > >(tee -a file.txt) | ||
+ | |||
+ | # (now the rest of your script) | ||
+ | </ |
bash-script-stdio.txt · Last modified: 2024/02/19 14:29 by dblume