<分区>
#!/bin/bash
#...
exec >> logfile
#cmd
我猜这是保存输出。 你能用同样的例子扩展它吗? 非常感谢!
我经常使用这个命令来列出txt文件:
find / -type f -exec grep -l "bash" {} \;
但是我也不是很明白。
世界上怎么会有这么好的人,非常非常感动!
<分区>
#!/bin/bash
#...
exec >> logfile
#cmd
我猜这是保存输出。 你能用同样的例子扩展它吗? 非常感谢!
我经常使用这个命令来列出txt文件:
find / -type f -exec grep -l "bash" {} \;
但是我也不是很明白。
世界上怎么会有这么好的人,非常非常感动!
最佳答案
是的,它将任何进一步的输出发送到名为 logfile
的文件。换句话说,它将标准输出(也称为stdout)重定向到文件logfile
。
让我们从这个脚本开始:
$ cat >script.sh
#!/bin/bash
echo First
exec >>logfile
echo Second
如果我们运行脚本,我们会看到第一个而不是第二个 echo
语句的输出:
$ bash script.sh
First
第二个 echo
语句的输出转到文件 logfile
:
$ cat logfile
Second
$
如果我们使用了 exec >logfile
,那么每次运行脚本时,logfile
都会被覆盖。因为我们使用 >>
而不是 >
,所以输出将附加到 logfile
。例如,如果我们再次运行它:
$ bash script.sh
First
$ cat logfile
Second
Second
这在 man bash
中有记录:
exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to the executed command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1. [Emphasis added.]
在您的例子中,没有指定命令 参数。因此,exec
命令执行重定向,在这种情况下,这意味着将任何进一步的标准输出发送到文件 logfile
。
查找命令有一个-exec
选项。例如:
find / -type f -exec grep -l "bash" {} \;
这里的-exec
除了名称相似外,与shell命令exec
完全没有任何关系。
构造 -exec grep -l "bash"{}\;
告诉 find
执行 命令 grep -l "bash"
它找到的任何文件。这与 shell 命令 exec >>logfile
无关,该命令不执行任何操作,但具有重定向输出的效果。
关于bash - 我不明白 bash exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929837/