如何将重定向命令本身包含到输出文件重定向中?例如
echo "hello!">output.txt
Run Code Online (Sandbox Code Playgroud)
我想要这样的输出文件的内容:
echo "hello!">output.txt
hello!
Run Code Online (Sandbox Code Playgroud)
Kus*_*nda 12
你可能想要这里的两件事之一。
使用tee
得到的结果echo
发送到终端,以及将文件:
$ echo 'hello!' | tee output
hello!
$ cat output
hello!
Run Code Online (Sandbox Code Playgroud)使用script
捕获整个终端会话:
$ script
Script started, output file is typescript
$ echo 'hello!' >output
$ cat output
hello!
$ exit
Script done, output file is typescript
Run Code Online (Sandbox Code Playgroud)
$ cat typescript
Script started on Sat Nov 10 15:15:06 2018
$ echo 'hello!' >output
$ cat output
hello!
$ exit
Script done on Sat Nov 10 15:15:37 2018
Run Code Online (Sandbox Code Playgroud)如果这不是您所要求的,那么请澄清您的问题。
在您要求的一般性中,这是不可能的。
要使用其他工具(类似于script
(1))实现这一点,该程序有必要观察您的 shell,在
command >foo
Run Code Online (Sandbox Code Playgroud)
foo
是文件名,并创建它。此外,shell 会尝试创建它,因此已经存在冲突。另外,如果程序会打印怎么办
command >foo
Run Code Online (Sandbox Code Playgroud)
到终端?
从 shell 内部来看,shell 的重定向过程从编程的角度来看是非常原始的(尝试找到他们自己构建原始 shell 的 C 讲座,这真的很令人惊讶)。
如果你真的需要这个,你就必须破解你自己的 shell 来拦截重定向并将命令传递到目标文件中。但是细节上可能有很多令人讨厌的问题......
您还可以管道整个外壳:
$ sh -i |& tee sh.log
sh-4.4$ hello
sh: hello: command not found
sh-4.4$ echo hi
hi
sh-4.4$ exit
Run Code Online (Sandbox Code Playgroud)
-i
尽管 stdout 不是终端,但仍需要保持 shell 交互。bash 和 zsh 也支持该选项。|&
管道标准输出和标准错误;它适用于 zsh 和 bash,但不适用于 sh(在那里,您需要2>&1 |
)。当然,您也可以使用&>
or2>&1 >
如果您只想重定向到一个文件,仅此而已。无论如何,sh.log
这里包含了一切。
$ cat sh.log
sh-4.4$ hello
sh: hello: command not found
sh-4.4$ echo hi
hi
sh-4.4$ exit
Run Code Online (Sandbox Code Playgroud)