DEV Community

Jeremy Kahn
Jeremy Kahn

Posted on

4

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:

#!/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)}'
view raw to-uppercase.sh hosted with ❤ by GitHub
#!/bin/bash
STD_IN=$(</dev/stdin)
echo $STD_IN | sed 's/-/_/g'
view raw to-snakecase.sh hosted with ❤ by GitHub

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more