DEV Community

Jeremy Kahn
Jeremy Kahn

Posted on

TIL: Reading stdin to a BASH variable

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)
Enter fullscreen mode Exit fullscreen mode

A full example:

With this, you can easily make pipe-able BASH script files. For instance, with these two files using this technique:

You can do:

echo some-text | ./to-uppercase.sh | ./to-snake-case.sh
Enter fullscreen mode Exit fullscreen mode

For:

SOME_TEXT
Enter fullscreen mode Exit fullscreen mode

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)