Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can bash read from piped input or else from the command line argument

Tags:

bash

pipe

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
like image 259
4 revs, 2 users 76% Avatar asked Apr 07 '15 21:04

4 revs, 2 users 76%


People also ask

How to read input from the command line in Bash?

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?

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.

Which Bash function accepts input from parameter or pipe?

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

How do I run a bash script from the command line?

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.


1 Answers

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:

  1. Read from a filename if supplied as an argument (regardless of whether stdin is a tty)
  2. Read from stdin if no file is supplied

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
like image 170
that other guy Avatar answered Oct 20 '22 20:10

that other guy