Bash script question

MrScott81

Golden Member
Aug 31, 2001
1,891
0
76
I primarily use ksh, but now I am being forced to use bash. In my scripting before, I used the read command extensively, but this doesn't seem to function the same with bash.

For example, the following works in ksh, but NOT in bash:

ksh:
$ echo 10 | read a
$ echo ${a}
10

bash:
$ echo 10 | read a
$ echo ${a}
<blank>

This is an overly simplified example, but I'm just wondering how to get the same functionality. Any help is appreciated!

 

QED

Diamond Member
Dec 16, 2005
3,428
3
0
Originally posted by: MrScott81
I primarily use ksh, but now I am being forced to use bash. In my scripting before, I used the read command extensively, but this doesn't seem to function the same with bash.

For example, the following works in ksh, but NOT in bash:

ksh:
$ echo 10 | read a
$ echo ${a}
10

bash:
$ echo 10 | read a
$ echo ${a}
<blank>

This is an overly simplified example, but I'm just wondering how to get the same functionality. Any help is appreciated!

This is because the "echo" and subsquent "read" commands are run in their own subshells. While inside the subshell, the shell variable "a" is properly set to "10". However, once the read command completes, this subshell process exits, and the shell variables modified are lost.

If you simply echo the value of the shell variable while still in the subshell process, you will get the result you desire:

$ echo 10 | ( read a; echo "a is " ${a} )
10

Note the parentheses around the read and second echo commands-- this causes these two commands to be run in the same subshell, and allows the second echo command to access the variable assigned with read command.