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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章