Piping in Bash (`echo "blah" | foo`)

In bash we can use the pipe character to pass some content to a command;
echo "blah" | foo
echo "blah" | foo
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;
function foo() { # I like brackets, sue me
echo "$@"
}
function foo() { # I like brackets, sue me
echo "$@"
}
Though running foo "blah" works as expected. I'm guessing $@ is not the correct symbol to use for this
3 Replies
WillsterJohnson
WillsterJohnsonOP2y ago
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.
function foo() {
# if $1 empty, use the piped content. Else use $1
local input=$1
if [[ -z $input ]]; then
read input
fi
echo "$input"
# do stuff
}
function foo() {
# if $1 empty, use the piped content. Else use $1
local input=$1
if [[ -z $input ]]; then
read input
fi
echo "$input"
# do stuff
}
Joao
Joao2y ago
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
WillsterJohnson
WillsterJohnsonOP2y ago
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
Want results from more Discord servers?
Add your server