exec shell 命令的选项 -l

Option -l of exec shell command

能否请您澄清一下 exec shell 命令的 -l 选项的用法。当我 运行 exec ls | catexec -l ls | cat.

时,我没有注意到任何区别

exec-l 选项在命令名称的开头添加了 -。例如:

exec -l diff | head

-diff: missing operand after '-diff'
-diff: Try '-diff --help' for more information.

注意 diff 之前的 -

这一切的意义何在?如果您在启动 shell 的命令之前有一个 -,它将充当登录 shell。来自 man bash:

A login shell is one whose first character of argument zero is a -, or one started with the --login option.

现在,man exec 指出:

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.

因此exec -l bash将运行bash作为登录shell。为了测试这一点,我们可以使用登录 bash 执行文件 ~/.bash_profile 的事实,因此:

$ cat ~/.bash_profile 
#!/bin/sh

printf "I am a login shell!\n"

如果我开始登录 bash,命令 printf "I am a login shell!\n" 将被执行。现在用 exec:

进行测试
$ exec bash
$

没有显示任何内容,我们处于未登录状态shell。

$ exec -l bash
I am a login shell!
$

这里我们有一个登录名shell。