12

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?

0

2 Answers 2

24

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
...
Sign up to request clarification or add additional context in comments.

Comments

0

Can you have this script check if it's running as sudo, and if it's not, exec itself with sudo?

#!/bin/bash
username='anthony'

if [[ -z "${SUDO_USER}" ]]; then
    exec sudo -H -u "${username}" -- $0
fi

echo "
# 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.