• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Bash script question

MrScott81

Golden Member
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!

 
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.

 
Back
Top