I would like to read some data either from pipe or from the command line arguments (say $1
), whichever is provided (priority has pipe).
This fragment tells me if the pipe was open or not but I don't know what to put inside in order not to block the script (test.sh
) (using read
or cat
)
if [ -t 0 ]
then
echo nopipe
DATA=$1
else
echo pipe
# what here?
# read from pipe into $DATA
fi
echo $DATA
Executing the test.sh
script above I should get the following output:
$ echo 1234 | test.sh
1234
$ test.sh 123
123
$ echo 1234 | test.sh 123
1234
The principal way to do this is via the read command. Although it is also possible to read input in the form of command line arguments that are passed to the Bash script when it is executed. In this tutorial, you will learn how to read input from the command line with a Bash script and the read command.
What is the equivalent of a bash pipe using command line arguments? Pipes and command line arguments are different forms of input that are not interchangeable. If a program allows you to have equivalent forms of both, that is the choice of that program alone.
Bash function that accepts input from parameter or pipe - Unix & Linux Stack Exchange I want to write the following bash function in a way that it can accept its input from either an argument or a pipe: b64decode() { echo "$1" | base64 --decode; echo } Desired usage: $ Stack Exchange Network
This can be done from the command line, with our script waiting for user input in order to proceed further. The principal way to do this is via the read command. Although it is also possible to read input in the form of command line arguments that are passed to the Bash script when it is executed.
You can read all of stdin into a variable with:
data=$(cat)
Note that what you're describing is non-canonical behavior. Good Unix citizens will:
This is what you see in sed
, grep
, cat
, awk
, wc
and nl
to name only a few.
Anyways, here's your example with the requested feature demonstrated:
$ cat script
#!/bin/bash
if [ -t 0 ]
then
echo nopipe
data=$1
else
echo pipe
data=$(cat)
fi
echo "$data"
$ ./script 1234
nopipe
1234
$ echo 1234 | ./script
pipe
1234
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With