linux命令之exec

exec命令我已知有两种用法:

  1. 用提供的命令替换当前shell, 其实就是子进程替换父进程
  2. 创建/重定向文件描述符

“用提供的命令替换当前shell”

$ help exec
exec: exec [-cl] [-a name] [command [arguments …]] [redirection …]
Replace the shell with the given command.

Execute COMMAND, replacing this shell with the specified program.
ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,
any redirections take effect in the current shell.

...

例子

#! /bin/sh
# exec-demo.sh
#

if [ x$1 = x1 ]; then # 如果第一个参数为1
    exec echo hello
else # 其他情况
    echo world
fi

echo end

执行如下:

$ chmod +x exec-demo.sh 
$ ./exec-demo.sh 
world
end
$ ./exec-demo.sh 1
hello

可以看到, 在调用exec后, 后面的内容就不会执行了.

更直观一点的例子:
新开一个terminal, 执行exec ls, 你会发现退出了终端.
因为子进程ls替换了父进程shell(新开的终端进程), 所以当ls结束, 终端就退出了.

创建/重定向文件描述符

直接看例子:

$ exec 100>&1 # 将文件描述符100连接到标准输出("备份"标准输出)
$ exec 1>hello.txt # 将标准输出重定向到文件hello.txt
$ echo hello # 并不会显示到终端, 已经到hello.txt中去了
$ echo world # 同上一步
$ exec 1>&100  # 将标准输出连接到100,这是之前保存的标准输出
$ exec 100>&- # 已经还原标准输出, 将原来的备份关了
$ echo show again
show again
$ cat hello.txt
hello
world

参考

https://blog.csdn.net/chaofanwei/article/details/19110739

发布了231 篇原创文章 · 获赞 77 · 访问量 52万+

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/104063331