bash - 如何将 bash 变量重定向到可执行文件?

标签 bash redirect

我有一个可执行文件,假设它叫做a.out。提示后需要两行输入 --

> ./a.out 
> give me input-1: 0 0 10
> give me input-2: 10 10 5
> this is the output: 20 20 20

我可以将输入存储在文件 (input.txt) 中并将其重定向到 a.out,文件如下所示 --

0 0 10
10 10 5

我可以像这样调用 a.out --

> ./a.out < input.txt
> give me input-1: 0 0 10 give me input-2: 10 10 5
> this is the output: 20 20 20

现在我想在该文件中存储多个输入并重定向到 a.out。该文件看起来像这样有 2 个输入 --

0 0 10
10 10 5
0 0 20
10 10 6

我正在写一个 bash 脚本,比如 --

exec 5< input.txt
while read line1 <&5; do
      read line2 <&5;
      ./a.out < `printf "$line1\n$line2"` ;
done

它不起作用,我该怎么做?

最佳答案

<需要包含内容的文件名,而不是内容本身。您可能只想使用管道:

exec 5< input.txt
while read line1 <&5; do
    read line2 <&5
    printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done

或进程替换:

exec 5< input.txt
while read line1 <&5; do
    read line2 <&5
    ./a.out < <(printf "%s\n%s\n" "$line1" "$line2")
done

不过,您不需要使用单独的文件描述符。只需将标准输入重定向到循环:

while read line1; do
    read line2
    printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done < input.txt

您也可以使用此处文档(但请注意缩进):

while read line1; do
    read line2
    ./a.out <<EOF
$line1
$line2
EOF
done < input.txt

或此处的字符串:

while read line1; do
    read line2
    # ./a.out <<< $'$line1\n$line2\n'
    ./a.out <<<"$line1
$line2"
done < input.txt

可以使用特殊的 $'...' 包含换行符引用,可以指定 换行 \n' ,或者字符串可以简单地嵌入换行符。


如果您使用 bash 4 或更高版本,您可以使用 -t检测输入结束的选项,因此 a.out可以直接从文件中读取。

# read -t 0 doesn't consume any input; it just exits successfully if there
# is input available.
while read -t 0; do
    ./a.out
done < input.txt

关于bash - 如何将 bash 变量重定向到可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979366/

相关文章:

regex - 编写 bash sed 命令时遇到问题 - 正则表达式匹配

php - htaccess 或 php 重定向到此任务?

.htaccess - 通过 htaccess 将一个特殊的 http URL 转发到带端口的 https URL

python - 拦截 bash 脚本函数/系统调用并将它们包装到自定义函数中

linux - 用于搜索和替换标签的 Bash 脚本

java - 通过java运行Shell脚本

linux - Bash 循环遍历日期时间 +%Y-%m-%d %H :%M format

linux - 狂欢 : wrong pipe output when using "sudo sh -c"

java - 重定向主页中的所有页面

jsf - URL 重定向不适用于 preRenderView 事件