#Bash 的 exec 命令
exec [OPTION]... [CMD [ARG]...]
功能
将进程上下文替换为指定的程序,或重定向当前 shell。
通常运行程时是创建子进程,程序执行完退出后会回到 shell。 通过这个命令运行程序时,并不创建进程,而是直接替换当前进程(shell)的上下文;程序退出就结束了,不会回到 shell。
类型
Bash 内置命令。
参数
OPTION选项:-a name- 将NAME作为CMD的第 0 个参数(伪造程序名)-c- 情况环境变量后执行CMD-l- 在CMD的第 0 个参数开头添加一个-(表示 login shell)
CMD- 要执行的命令;如果没有指定CMD则对当前 shell 进行重定向ARG- 命令CMD的参数
#示例
替换进程
#!/usr/bin/bash
# 进行一些配置
source ./.venv/
# 将进程替换为 python
exec python main.py
- 运行 python 时不会保留 bash 进程;节省资源
重定向
$ exec > log.txt # 将当前 bash 的标准输出重定向到 log.txt
$ exec 2 > err.txt # 将当前 bash 的标准错误重定向到 err.txt
$ echo Hello World # 输出到 log.txt
$ echo Error > &2 # 输出到 err.txt
#手册
exec: exec [-cl] [-a name] [command [argument ...]] [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.