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.

    Options:
      -a name   pass NAME as the zeroth argument to COMMAND
      -c        execute COMMAND with an empty environment
      -l        place a dash in the zeroth argument to COMMAND

    If the command cannot be executed, a non-interactive shell exits, unless
    the shell option `execfail' is set.

    Exit Status:
    Returns success unless COMMAND is not found or a redirection error occurs.

1 用新的shell替换原来的shell.

如果你替换后,输入exec命令是不能退回到原来的shell的。就其原因是因为:系统调用exec是以新的进程去代替原来的进程,但进程的PID保持不变。因此,可以这样认为,exec系统调用并没有创建新的 进程,只是替换了原来进程上下文的内容。原进程的代码段,数据段,堆栈段被新的进程所代替。

2 用新的程序(命令)替换原来的shell.

当程序执行完后会退出,也就看起来是终端会自动退出,其实终端早已经被替换了。

3 find命令与exec结合,如下:

在当前目录下(包含子目录),查找所有txt文件并找出含有字符串"bin"的行

find ./ -name "*.txt" -exec grep "bin" {} \;

在当前目录下(包含子目录),删除所有txt文件

find ./ -name "*.txt" -exec rm {} \;

4 选项:

-a 如果你在exec后添加-a选项,则该选项后面的name参数 将作为位置参数$0的值,本来$0的值为当前进程所对应的命令的名字。

pur@DESKTOP-HSUIF14:/mnt/c/Users/Pur$ exec -a pur bash
pur@DESKTOP-HSUIF14:/mnt/c/Users/Pur$ echo $0
pur
pur@DESKTOP-HSUIF14:/mnt/c/Users/Pur$ exec bash
pur@DESKTOP-HSUIF14:/mnt/c/Users/Pur$ echo $0
bash

-c 以空环境运行命令;

-l 在COMMAND 命令的第0个参数中加一个短线,在做一个小例子:

root@kali:~# exec -a pur -l bash
root@kali:~# echo $0
-pur

results matching ""

    No results matching ""