Operating System - HP-UX
1751836 Members
5287 Online
108782 Solutions
New Discussion

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

 
support_billa
Valued Contributor

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

 

 

1 REPLY 1

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 run :

 

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 run 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.


I am an HPE Employee
Accept or Kudo