如何将bash变量重定向到可执行文件?
我有一个可执行文件,说它叫a.out
。这需要输入的两行的提示后 -如何将bash变量重定向到可执行文件?
> ./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
'HERESTRING'也可以工作(不需要子shell)。 – 2014-09-22 17:18:26
我刚刚添加了一个here字符串,但后来决定只添加一个here文档,因为在这里字符串中嵌入换行符需要另一个新语法('$'... \ n ...'')或者看起来几乎完全像这里的doc一样。 – chepner 2014-09-22 17:20:24
+1为'-t'选项 – user000001 2014-09-22 17:25:18
这可能有助于更具体地描述你的最终尝试不能正确工作。 (如果没有别的,从一般的高质量问题角度来看)。 – 2014-09-22 17:18:54
使用'printf'%s \ n'“$ line1”“$ line2”''更安全。这样,如果'line1'或'line2'中的任何内容读取为格式字符串,则不会引入错误。 – 2014-09-24 16:30:58