首页 > 解决方案 > 使用 bash 自动安装脚本

问题描述

我正在尝试脚本安装以下内容,如何在命令中的提示符处回答“y”

 wget -O - mic.raspiaudio.com | sudo bash

我已经尝试过通常的方法,但这不起作用

echo "y" |  wget -O - mic.raspiaudio.com | sudo bash

标签: linuxbash

解决方案


免责声明:以下解决方案适用于具有非交互式开关的脚本。

我相信这echo不会起作用,因为它没有写入产生的/dev/tty那个bash。您可以使用bash提供的默认功能来执行此操作。

从手册页:

-c        If the -c option is present, then commands are read from the first 
          non-option argument command_string.  If there are arguments after the
          command_string,  the  first argument is assigned to $0 and any remaining
          arguments are assigned to the positional parameters.

如果您-c在 bash 中使用选项,您可以为将运行的脚本提供参数,这些参数将按照手册页中的说明进行放置。例如: bash -c "script" "arg0" "arg1" ...。将arg0被放入$0arg1将被放入$1等等。

现在,我不知道这是否可以概括,但这个解决方案只有在脚本中有非交互模式时才有效。

如果您看到脚本,它具有以下功能:

FORCE=$1

confirm() {
    if [ "$FORCE" == '-y' ]; then
        true
    else
        read -r -p "$1 [y/N] " response < /dev/tty
        if [[ $response =~ ^(yes|y|Y)$ ]]; then
            true
        else
            false
        fi
    fi
}

并用作:

if confirm "Do you wish to continue"
then
  echo "You are good to go"
fi

因此,如果我们可以将 $1 设置为“-y”,它不会要求确认,我们将尝试通过以下方式执行相同操作:

$ bash -c "$( wget -qO - mic.raspiaudio.com)" "dummy" "-y"

这应该适用于脚本,前提是它没有任何其他交互选项。我没有用我自己的最小脚本测试原始脚本,它似乎可以工作。例如:

$ bash -c "$(wget -qO - localhost:8080/test.sh)" "dummy" -y
You are good to go
$ bash -c "$(wget -qO - localhost:8080/test.sh)"
Do you wish to continue [y/N] y
You are good to go

推荐阅读