简体   繁体   中英

How to assign stdin arguments to variables in BASH from Pipe

What I'm trying:

I'm trying to assign args to a variable if it is from Pipe

Expected:

What should I do inside my script to assign the arguments to variables so that they look like this?

if [ -p /dev/stdin ]; then
    option1="one"
    option2="two"
    option3="three"
    echo "$option1" "$option2" "$option3"
else
    echo "no input"
fi

Input: echo one two three |./myscript
Output: one two three

Question Update: I need all the arguments presented before the |(pipe) as just string input to my script. It should not check for existence or execute the binary(here the binary is echo ) present before the |(pipe).

Input: echo one two three |./myscript
Output: echo one two

The words one , two , three in echo one two three |./myscript are arguments of echo ; but to ./myscript they are only input, not arguments.

Reading "arguments" from stdin

To read each word into its own variable use

if [ -p /dev/stdin ]; then
    read -r option1 option2 option3 
    echo "$option1" "$option2" "$option3"
else
    echo "no input"
fi

If you want to allow an arbitrary number of words, use an array.
read -ra myArray reads all words from a single line into an array.
mapfile -t myArray reads all lines into an array.
read -rd '' -a myArray reads all words from all lines into an array.

To access the words in the array, use ${myArray[0]} , ${myArray[1]} , ..., ${myArray[${#myArray[@]}-1]} .

Using actual arguments

Instead of parsing stdin it might be better to use actual arguments. To do so, execute your script like ./myscript one two three . Then access the arguments using positional parameters:

if [ $# = 0 ]; then
   echo "no arguments"
else
   echo "The arguments are $1 $2 $3 ..."
fi

For an arbitrary number of arguments check out shift and $@ .

You should probably simply use xargs instead. But what you ask isn't hard to do per se.

if [ -p /dev/stdin ]; then
    read -r option1 option2 option3
    echo "$option1" "$option2" "$option3"
else
    echo "no input"
fi

With xargs , this would look like

option1=$1
option2=$2
option3=$3

and then you'd just run it with

echo first second third |
xargs ./yourscript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM