Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
Languages and Scripting
Showing results for 
Search instead for 
Did you mean: 

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

Valued Contributor

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



 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 ?





Duncan Edmonstone
Honored Contributor

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


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



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.