bash 读取命令不等待输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15744421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:02:55  来源:igfitidea点击:

read command doesn't wait for input

bashwaitreadline

提问by mohammadh montazeri

I have problem executing a simple script in bash. The script is like this:

我在 bash 中执行一个简单的脚本时遇到问题。脚本是这样的:

#! /bin/sh

read -p 'press  [ENTER]  to continue deleting line'
sudo sed -ie '$d' /home/hpccuser/.profile

and when I execute the script with ./script the output is like this:

当我用 ./script 执行脚本时,输出是这样的:

press  [ENTER]  to continue deleting line./script: 3: read: arg count
[sudo] password for user

I run the read command directly in terminal (copy and paste from script to terminal) and it works fine; it waits for an ENTER to be hit (just like a pause).

我直接在终端中运行读取命令(从脚本复制并粘贴到终端)并且它工作正常;它等待按下 ENTER 键(就像暂停一样)。

回答by Charles Duffy

Because your script starts with #!/bin/shrather than #!/bin/bash, you aren't guaranteed to have bash extensions (such as read -p) available, and can rely only on standards-compliant functionality.

由于您的脚本以#!/bin/sh而非开头#!/bin/bash,因此不能保证您有read -p可用的bash 扩展(例如),并且只能依赖符合标准的功能。

See the relevant standards documentfor a list of functionality guaranteed to be present in read.

请参阅相关的标准文件的要求被提供在功能列表read

In this case, you'd probably want two lines, one doing the print, and the other doing the read:

在这种情况下,您可能需要两行,一行进行打印,另一行进行读取:

printf 'press [ENTER] to continue deleting...'
read _

回答by Pouya

You can do this with echo command too!:

您也可以使用 echo 命令执行此操作!:

    echo "press  [ENTER]  to continue deleting line"
    read continue

回答by hiten

Seems I'm late to the party, but echo -n "Your prompt" && sed 1qdoes the trick on a POSIX-compliant shell. This prints a prompt, and grabs a line from STDIN.

似乎我迟到了,但是echo -n "Your prompt" && sed 1q在符合 POSIX 的 shell 上做到了这一点。这会打印一个提示,并从 STDIN 中抓取一行。

Alternatively, you could expand that input into a variable:

或者,您可以将该输入扩展为变量:

echo -n "Your prompt"
YOUR_VAR=$(sed 1q)

回答by chr

read -p " Ici mon texte " continue

it works on raspbian

它适用于 raspbian