谁能用简单的例子解释exec命令在shell脚本中的用途吗?
该exec
内核中的内置命令镜功能,还有他们家的基础上execve
,这通常是由被称为C.
exec
在当前进程中替换当前程序,而无需fork
执行新进程。并不是您在编写的每个脚本中都会使用它,但有时会派上用场。这是我使用过的一些场景;
我们希望用户在不访问外壳的情况下运行特定的应用程序。我们可以在/ etc / passwd中更改登录程序,但是也许我们希望从启动文件中使用环境设置。因此,在(say)中.profile
,最后一条语句表示如下内容:
exec appln-program
所以现在没有外壳可以回去了。即使appln-program
崩溃,最终用户也无法进入shell,因为它不存在-被exec
替换了。
我们要使用与/ etc / passwd中不同的shell。看起来很愚蠢,有些网站不允许用户更改其登录外壳。我知道有一个站点,每个人都从这里开始csh
,每个人都.login
将对的调用放入(csh启动文件)ksh
。在此csh
过程中,它留下了一个混乱的进程,并且注销是两个阶段,可能会造成混乱。因此,我们将其更改为exec ksh
仅用korn shell替换了c-shell程序,并使一切变得更简单(与此相关的还有其他问题,例如,事实ksh
不是登录shell)。
只是为了节省流程。如果我们打电话prog1 -> prog2 -> prog3 -> prog4
等,再也不回头,那么让每个电话都执行一次。这样可以节省资源(当然,除非重复,否则可以节省很多资源),并且使关机更加简单。
您显然已经exec
在某处使用过,也许如果您显示的代码有问题,我们可以证明其使用是合理的。
编辑:我意识到我上面的答案是不完整的。in shell有两种用法,exec
例如ksh
和bash
-用于打开文件描述符。这里有些例子:
exec 3< thisfile # open "thisfile" for reading on file descriptor 3
exec 4> thatfile # open "thatfile" for writing on file descriptor 4
exec 8<> tother # open "tother" for reading and writing on fd 8
exec 6>> other # open "other" for appending on file descriptor 6
exec 5<&0 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4 # copy write file descriptor 4 onto 7
exec 3<&- # close the read file descriptor 3
exec 6>&- # close the write file descriptor 6
请注意,间距在这里非常重要。如果在fd数字和重定向符号之间放置空格,则exec
恢复为原始含义:
exec 3 < thisfile # oops, overwrite the current program with command "3"
有几种方法可以使用它们,例如,在kshread -u
或print -u
上使用bash
,例如:
read <&3
echo stuff >&4
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句