Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script not waiting on read

Tags:

bash

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?

like image 830
alukach Avatar asked Aug 09 '12 22:08

alukach


1 Answers

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
...
like image 110
William Pursell Avatar answered Nov 16 '22 02:11

William Pursell