2016-08-29 29 views
3

我有一堆其中操縱命令行參數,並在年底調用另一個版本之前做一些東西包裝的shell腳本。是否有任何理由不總是exec最後的二進制?這似乎會更簡單,更高效,但我從來沒有看到它完成。任何不在shell腳本中執行的理由?

+1

這取決於你想繼續使用shell或不?如果沒有,那麼繼續使用'exec',但是如果你想在程序/腳本結束後繼續使用shell,那麼你不能使用'exec'。如果你讀了例如[Bash的手冊頁(http://man7.org/linux/man-pages/man1/bash.1.html),你將看到'exec'命令「...取代了殼」。 –

回答

4

如果您檢查/usr/bin,您可能會發現很多很多shell腳本以exec命令結尾。只是作爲一個例子,這裏是/usr/bin/ps2pdf(Debian的):

#!/bin/sh 
# Convert PostScript to PDF. 

# Currently, we produce PDF 1.4 by default, but this is not guaranteed 
# not to change in the future. 
version=14 

ps2pdf="`dirname \"$0\"`/ps2pdf$version" 
if test ! -x "$ps2pdf"; then 
____ps2pdf="ps2pdf$version" 
fi 
exec "$ps2pdf" "[email protected]" 

exec的使用,因爲它消除了對保持殼過程中它不再需要主動後的需要。

/usr/bin目錄具有使用exec超過150 shell腳本。所以,使用exec是很常見的。

不使用exec的原因是,如果有一些處理要完成二進制完成執行。

4

我不同意您的看法,這是不是一個普遍的做法。這就是說,它不是總是是正確的。

,我結束與另一個命令的執行腳本時,最常見的情況,但不能合理使用exec,就是如果我需要清理鉤在年底完成命令後運行。例如:

#!/bin/sh 

# create a temporary directory 
tempdir=$(mktemp -t -d myprog.XXXXXX) 
cleanup() { rm -rf "$tempdir"; } 
trap cleanup 0 

# use that temporary directory for our program 
exec myprog --workdir="$tempdir" "[email protected]" 

...執行後不會實際清理tempdir!改變這種exec myprog僅僅myprog有一些缺點 - 由殼體,一個額外的進程表項持續的內存使用情況,信號可能被傳遞到外殼,而不是在於它的執行程序 - 但它也保證了外殼仍然在myprog的出口處運行所需的任何陷阱。