我有一些使用参数的脚本,它们工作得很好,但我希望它们能够从stdin中读取,例如,从管道中读取,例如,假设这称为read:
#!/bin/bash
function read()
{
echo $*
}
read $*
现在,这可以与read "foo" "bar"
一起使用,但我想将其用作:
echo "foo" | read
我该如何做到这一点?
发布于 2013-09-12 18:04:42
您可以使用<<<
来获得此行为。read <<< echo "text"
应该能成功。
使用readly
进行测试(我不喜欢使用保留字):
function readly()
{
echo $*
echo "this was a test"
}
$ readly <<< echo "hello"
hello
this was a test
使用管道,基于this answer to "Bash script, read values from stdin pipe"
$ echo "hello bye" | { read a; echo $a; echo "this was a test"; }
hello bye
this was a test
发布于 2015-05-30 01:02:25
下面是使用printf
和标准输入的bash中sprintf
函数的实现示例:
sprintf() { local stdin; read -d '' -u 0 stdin; printf "$@" "$stdin"; }
示例用法:
$ echo bar | sprintf "foo %s"
foo bar
这将使您了解函数如何从标准输入中读取。
发布于 2018-05-12 03:04:33
我发现使用test
和awk
可以在一行内完成这项工作……
test -p /dev/stdin && awk '{print}' /dev/stdin
test -p
测试管道上的输入,管道通过标准输入接受输入。只有当输入存在时,我们才想要运行awk
,否则它将无限期地挂起,等待永远不会到来的输入。
我已经将其放入一个函数中,以使其易于使用。
inputStdin () {
test -p /dev/stdin && awk '{print}' /dev/stdin && return 0
### accepts input if any but does not hang waiting for input
#
return 1
}
用法...
_stdin="$(inputStdin)"
另一个函数在没有测试的情况下使用awk等待命令行输入...
inputCli () {
local _input=""
local _prompt="$1"
#
[[ "$_prompt" ]] && { printf "%s" "$_prompt" > /dev/tty; }
### no prompt at all if none supplied
#
_input="$(awk 'BEGIN {getline INPUT < "/dev/tty"; print INPUT}')"
### accept input (used in place of 'read')
### put in a BEGIN section so will only accept 1 line and exit on ENTER
### WAITS INDEFINITELY FOR INPUT
#
[[ "$_input" ]] && { printf "%s" "$_input"; return 0; }
#
return 1
}
用法...
_userinput="$(inputCli "Prompt string: ")"
请注意,第一个printf
上的> /dev/tty
似乎是在命令替代$(...)
中调用函数时打印提示所必需的。
这种awk
的使用允许消除用于从键盘或标准输入收集输入的奇怪的read
命令。
https://stackoverflow.com/questions/18761209
复制相似问题