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!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay