As L. Scott Johnson correctly found, the read
reads from standard input. The standard input in the shell that su
runs is connected to the here-document, so the read
reads the literal string echo "the name is "
(note that since the here-document is unquoted, the $name
has already been expanded to an empty string, or to whatever value it had in the calling shell).
Here is the same thing, but with a quoted here-document, and an extra line outputting $name
again:
su username <<'SESSION' set -x echo -n "Enter your name and press [ENTER]: " read name echo "the name is $name" echo "What I read was $name" SESSION
The output would be
Password: + echo -n Enter your name and press [ENTER]: Enter your name and press [ENTER]: + read name + echo What I read was echo "the name is $name" What I read was echo "the name is $name"
To correctly do this, you can't have read
reading from standard input. Instead, open a new file descriptor as a copy of standard input, and get read
to read from that:
su username 3<&0 <<'SESSION' set -x echo -n "Enter your name and press [ENTER]: " read name <&3 echo "the name is $name" SESSION
If the shell of the other user is bash
or ksh
, then read name <&3
may be replaced by read -u3 name
.
Note however that you can't expect the name
variable to be set in the shell calling su
as a child shell can't modify the environment (variables etc.) of a parent shell.