bash - 我不明白 bash exec

标签 bash exec

<分区>

#!/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

查找命令有一个-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/

相关文章:

c - fork exec 等待命令行输入值的循环

java - Intellij Idea中使用 "Runtime.getRuntime().exec"方法时如何设置JAVA_HOME?

php - Unoconv/libreoffice 命令行转换很慢

c - 在管道命名程序中执行 exec() 函数

sockets - os.execute 不继承父级的 fds

linux - 使用 sed 或 awk 重命名多个文件

mysql - gunzip 和 mysql 导入 - 没有这样的文件或目录

bash - 如何将 org 文件中的最新条目输出并格式化到终端?

macos - 如何使 bash 制表符完成功能像 Windows 的 cmd.exe 一样工作?

bash - Prolog 中从字符串到列表的转换