简体   繁体   中英

Pass bash array to stdin

I currently have a bash script like this, which successfully calls the program prog :

#!/bin/bash
var1=hello
var2=world
prog <<EOF
$var1
$var2
EOF

Instead of var1 and var2 , how would I pass each element within an array (of unknown length, since I am using $@) to prog in the same manner?

Strictly speaking, you would want something like

for line in "$@"; do
    echo "$line"
done | prog

It's not a here document, but it has the same effect. Here documents and arrays were developed for two different use cases.

Even more strictly speaking, $@ is not an array, although it tries very hard to behave like one. :)

You could loop over each element of the array and echo each value into the program:

vars=('foo' 'foo bar' 'bar')
for var in "${vars[@]}"; do echo $var; done | prog

FAIRNESS UPDATE : @chepner beat me to this answer by a few seconds :)

As far as I know, you cannot pass variables , but you can pass arguments , so here's a fix:

prog $VAR1 $VAR2 <<EOF

And inside prog you could use:

ARR=($@)

to save all the positional parameters to the variable ARR .

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