在从管道执行的bash脚本中使用read -p [英] Using read -p in a bash script that was executed from pipe

查看:238
本文介绍了在从管道执行的bash脚本中使用read -p的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我事先表示歉意-我不太清楚我要问的内容背后的想法,以了解为什么它不起作用(我不知道我需要学习什么).我首先在堆栈交换中搜索了答案-我发现了一些看起来可能相关的信息,但是对这些概念的解释不够好,以至于我不了解如何构建有效的解决方案.我一直在搜寻google,但没有找到任何能准确描述正在发生的事情的信息(据我了解).可以帮助我了解正在发生的事情的背景概念的任何方向,将不胜感激.

I apologize in advance - I don't fully understand the ideas behind what I'm asking well enough to understand why it's not working (I don't know what I need to learn). I searched stack exchange for answers first - I found some information that seemed possibly relevant, but didn't explain the concepts well enough that I understood how to build a working solution. I've been scouring google but haven't found any information that describes exactly what's going on in such a way that I understand. Any direction to background concepts that may help me understand what's going on would be greatly appreciated.

是否可以在通过管道执行的bash脚本中获取用户输入?

例如:

wget -q -O - http://myscript.sh | bash

在脚本中:

read -p "Do some action (y/n): " __response
if [[ "$__response" =~ ^[Yy]$ ]]; then
   echo "Performing some action ..."
fi

据我所知,这是行不通的,因为读取尝试从stdin读取输入,并且bash脚本当前正在通过该管道执行"(我敢肯定有一种更准确的技术来描述什么是发生,但我不知道如何.)

As I understand it, this doesn't work because read attempts to read the input from stdin and the bash script is currently "executing through that pipe" (i'm sure there is a more technical accurate way to describe what is occurring, but i don't know how).

我找到了建议使用的解决方案:

I found a solution that recommended using:

read -t 1 __response </dev/tty

但是,这也不起作用.

任何阐明我需要了解才能使它起作用的概念,或者对为什么它不起作用或解决方案的解释将不胜感激.

Any light shed on the concepts I need to understand to make this work, or explanations of why it is not working or solutions would be greatly appreciated.

推荐答案

tty解决方案有效.使用以下代码对其进行测试,例如:

The tty solution works. Test it with this code, for example:

$ date | { read -p "Echo date? " r </dev/tty ; [ "$r" = "y" ] && cat || echo OK ; }
Echo date? y
Sat Apr 12 10:51:16 PDT 2014
$ date | { read -p "Echo date? " r </dev/tty ; [ "$r" = "y" ] && cat || echo OK ; }
Echo date? n
OK

read中的提示出现在终端上,read等待响应,然后再决定是否回显日期.

The prompt from read appears on the terminal and read waits for a response before deciding to echo the date or not.

我在上面写的内容与以下代码行在两个关键方面有所不同:

What I wrote above differs from the line below in two key aspects:

read -t 1 __response </dev/tty

首先,选项-t 1使read的超时时间为一秒.其次,此命令不提供提示.两者的结合可能意味着,即使read简短地要求输入,您也不知道.

First, the option -t 1 gives read a timeout of one second. Secondly, this command does not provide a prompt. The combination of these two probably means that, even though read was briefly asking for input, you didn't know it.

这篇关于在从管道执行的bash脚本中使用read -p的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆