Piping in Bash (`echo "blah" | foo`)
In bash we can use the pipe character to pass some content to a command;
If I'm the author of the command
foo
, how can I access that content. eg "blah"
?
As I understand it, "blah"
should be the stdin for foo
, however when I write the following implementation I get no result;
Though running foo "blah"
works as expected. I'm guessing $@
is not the correct symbol to use for this3 Replies
read
You use read
for this. Man, I suck at bash
For the archive, here's a snippet which resolves an input from either $1
or piped content.
It doesn't have a mechanism for knowing if both are empty, so you'll have to implement that yourself.
Bash sucks, rather. It's the opposite of intuitive and it's an ugly language all around. Even more so than PHP (in contrast it makes PHP look like a work of art)
I only use it because it's convenient but anything longer than a few lines of code and I'm already switching to Python or something else
Usually I can get the behavior I'm looking for through a mix of Copilot, Google, and my own limited knowledge (https://github.com/WJUtils/bash was written almost entirely by Copilot under my instruction) but somehow neither Copilot nor Google were helpful here.
I only realised I could use
read
because after posting this I got to page 6 of Google and said out loud "how the fuck do I read the pipe?" and immediately facepalmed as I realised there's literally a command called "read"
If I'm doing something which isn't terminal-specific I'll always go for TypeScript/JavaScript as they're ususally faster than Python and I'm yet to have a use case which doesn't have an npm package I can leverage, Python is still on the cards for me though despite me not being much of a fan