Bash脚本不等待阅读

时间:2012-08-09 22:12:39

标签: bash

我正在尝试以另一个用户身份运行命令并以该用户身份读取输入。出于某种原因,脚本不会在read命令上暂停,我不确定为什么。以下是该脚本的示例:

#!/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"

关于为什么这不会停留在read nameread email

的任何想法

2 个答案:

答案 0 :(得分:20)

read从stdin读取,bash从sudo继承其stdin,它来自heredoc。如果你想让它来自其他地方,你需要明确。例如:

bash  3<&0 << 'END_COMMAND'
...
read <&3
...

但这不适用于sudo,因为sudo关闭了非标准文件描述符。但是sudo并没有关闭stderr,所以如果你能够重复使用那个文件描述符,你可以做到:

sudo -H -u "$username" bash 2<&0 << 'END_COMMAND'
...
read -u 2 email
...

但这样做可能更安全:

sudo -H -u "$username" bash << 'END_COMMAND'
...
read email < /dev/tty
...

答案 1 :(得分:0)

你是否可以检查这个脚本是否以sudo身份运行,如果不是,请使用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