Today I wanted to read stdin to a BASH script variable for additional processing. It's not completely straightforward, but it's pretty easy once you know the syntax:
YOUR_VARIABLE=$(</dev/stdin)
A full example:
#!/bin/bash | |
# Usage: | |
# echo 'hello!' | ./read-stdin-to-variable.sh | |
# https://stackoverflow.com/a/15269128 | |
STD_IN=$(</dev/stdin) | |
echo "Echoing stdin:" | |
echo "$STD_IN" | |
echo "Echoing again:" | |
echo "$STD_IN" |
With this, you can easily make pipe-able BASH script files. For instance, with these two files using this technique:
#!/bin/bash | |
STD_IN=$(</dev/stdin) | |
# https://stackoverflow.com/a/27480719 | |
echo $STD_IN | awk '{print toupper($0)}' |
#!/bin/bash | |
STD_IN=$(</dev/stdin) | |
echo $STD_IN | sed 's/-/_/g' |
You can do:
echo some-text | ./to-uppercase.sh | ./to-snake-case.sh
For:
SOME_TEXT
Shoutout to StackOverflow user Ingo Karkat for explaining this. It's a very handy little trick for making BASH scripts more flexible and reusable!
Top comments (0)