Operating System - Linux
1748112 Members
3302 Online
108758 Solutions
New Discussion юеВ

scripting on bash - reading values to multiple variables

 
SOLVED
Go to solution
itai weisman
Super Advisor

scripting on bash - reading values to multiple variables

hello,
on ksh - the following syntax would work -
echo 1 2 3 | read a b c
a would contain '1', b would contain '2' and c would be 2.
on bash it wouldn't work... no data will be read into these variables.
does anyone know how can I do that on bash? looking for elegant solution. I don't want set each variable seperatly.
thanks
ITai
2 REPLIES 2
Hemmetter
Esteemed Contributor
Solution

Re: scripting on bash - reading values to multiple variables

Hi ITai,

from ksh(1) "ksh -- Public domain korn shell"

section "BUGS"
<...>
BTW, the most frequently reported bug is
echo hi | read a; echo $a # Does not print hi
I'm aware of this and there is no need to report it.



Bash:
$ A=( $( echo X Y Z) )
$ echo ${A[2]}
Z
$echo ${A[*]}
X Y Z




rgds
HGH

Mike Stroyan
Honored Contributor

Re: scripting on bash - reading values to multiple variables

This topic also appears as question E4 of the bash FAQ at http://tiswww.case.edu/php/chet/bash/FAQ .
The trick is that the variables are set but the values don't come back from the child shell that reads the pipe to the parent shell that you want the variables set in. You can instead use `echo 1 2 3` or $(echo 1 2 3) to expand the output of a command into arguments for another statement.

One way to rewrite it in bash or recent ksh is with a 'here string'-

read a b c <<< $(echo 1 2 3)