I'm trying to run commands as another user and read input as that user. For some reason the script doesn't pause on the read
command, I'm unsure as to why. Here's an example of the script:
#!/bin/bash
username='anthony'
sudo -H -u "$username" bash << 'END_COMMAND'
# Commands to be run as new user
# -------------------------------
echo "#! Running as new user $USER..."
echo "#! Gathering setup information for $USER..."
echo -n "Enter your name and press [ENTER]: "
read name
echo -n "Enter your email and press [ENTER]: "
read email
END_COMMAND
echo "Done"
Any ideas as to why this isn't stopping on read name
or read email
?
read
is reading from stdin, and bash
is inheriting its stdin from sudo, which is coming from the heredoc. If you want it to come from somewhere else, you need to be explicit. For example:
bash 3<&0 << 'END_COMMAND'
...
read <&3
...
This does not work with sudo, however, since sudo closes the non-standard file descriptors. But sudo does not close stderr, so if you can get away with reusing that file descriptor, you might be able to do:
sudo -H -u "$username" bash 2<&0 << 'END_COMMAND'
...
read -u 2 email
...
But it's probably much safer to do:
sudo -H -u "$username" bash << 'END_COMMAND'
...
read email < /dev/tty
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With