Re: ksh : HP-UX vs Linux : using of "read" (606 Views)
Reply
Valued Contributor
support_billa
Posts: 192
Registered: ‎06-27-2011
Message 1 of 2 (611 Views)

ksh : HP-UX vs Linux : using of "read"

 hello,

 

 In ksh : HP-UX it works:

 

 echo "a b c" | read a b c

 echo "${b:-"notset"}"

 output : b

 

 

 In ksh : Linux Red Hat  it doesn't works

 

 echo "a b c" | read a b c

 echo "${b:-"notset"}"

 output : notset

 

 hmm , why ?

 

 in some tests i parse an output of an command like "lvdisplay"  to variables  with "read" , in the variable is only "\n"

 

 i have no idea of the reason ?

 

 regards

 

 

Honored Contributor
Duncan Edmonstone
Posts: 5,684
Registered: ‎08-05-2000
Message 2 of 2 (606 Views)

Re: ksh : HP-UX vs Linux : using of "read"

Ah the joys of shell implementations!

 

It would be nice to think that all shells are created to follow some level of reasonably consistent logic, particularly when they are supposed to be implementations of the same shell. Alas this is not the case... the problem here is that, particlarly on older shell implementations, there was no guidance on which "side" of a pipeline would run in a subshell, resulting in the kind of things you see!

 

Whatever implementation of ksh you have on your Linux box is obviously running the subshell on the right of the pipe, so when you execute:

 

echo "a b c" | read a b c

The "read a b c" part is run in a subshell, the result being, as soon as you are onto a new shell command/statement you have exited that subshell where the variables a, b, and c were actually set. On HP-UX, the echo statement is the one running in the sub-shell, so no problem. Bad news for your "portable" script!

 

One way around this, is of course to use a while loop so everthing in the loop is executed in the sub-shell as well. For example, you might change your code above to:

 

echo "a b c" | while read a b c

do

echo "${b:-"notset"}"

done

 

But that may not work in every real life situation - otherwise if you can't find a "newer" shell (I think most ksh93 compatible implementations of the ksh shell on Linux don't suffer this problem) you will need to re-think your script to avoid this sort of variable assignement via the read command.


HTH

Duncan
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.