2014-05-24 22 views
3

我想在shell中運行某些操作,具體取決於當前目錄中的默認生成文件是否包含特定目標。如何在生成文件中檢查目標的存在

#!/bin/sh 
make -q some_target 
if test $? -le 1 ; then 
    true # do something 
else 
    false # do something else  
fi 

這是有效的,因爲如果目標不存在,GNU make返回錯誤代碼2,否則返回0或1。問題是沒有以這種方式記錄。這裏是男人的一部分:

-q, --question 
     ``Question mode''. Do not run any commands, or print anything; 
     just return an exit status that is zero if the specified targets 
     are already up to date, nonzero otherwise. 

只有零/非零區分。什麼是正確的方法來做到這一點?

回答

2

您應該閱讀the GNU make manual而不是手冊頁:手冊頁僅僅是一個摘要而非完整的定義。該手冊說:

The exit status of make is always one of three values: 

0 The exit status is zero if make is successful 

2 The exit status is two if make encounters any errors. It will print messages 
    describing the particular errors. 

1 The exit status is one if you use the ‘-q’ flag and make determines that 
    some target is not already up to date. 

由於試圖創建一個不存在的目標是一個錯誤,你總是會在這種情況下得到一個退出碼2。

+0

所以沒有辦法從其它任何區分這種錯誤,而是通過解析stderr輸出? – sshilovsky

+0

正確; make不會爲可能遇到錯誤的每種可能方式使用不同的錯誤代碼。 – MadScientist

2

遲到的答案,但也許它會幫助人們在未來面臨同樣的問題。

我使用下面的方法,它需要您修改Makefile(您需要添加一個%-rule-exists模式規則)。如果你不想這樣做,你可以直接從你的腳本運行make -n your-target-to-check &> /dev/null

我使用它來獲得autobuild和autoupload等命令,這些命令包含在代碼片段中的上下文中。

%-rule-exists: 
    @$(MAKE) -n $* &> /dev/null 


auto%: %-rule-exists 
    $(info Press CTRL-C to stop $*ing) 
    @while inotifywait -qq -r -e move -e create -e modify -e delete --exclude "\.#.*" src; do make $* ||: ; date ; done 

輸出示例:

$ make build-rule-exists; echo Exit code: $? 
Exit code: 0 
$ make nonsense-rule-exists; echo Exit code: $? 
Exit code: 2 

注意,它實際上並沒有建立目標,以找出是否該規則存在的make-n標誌的禮貌。即使構建失敗,我也需要它來工作。

2

另一種可能性是,從讀入makefile導致數據庫中的grep:

some_target:   
    @ if $(MAKE) -C subdir -npq --no-print-directory .DEFAULT 2>/dev/null | grep -q "^[email protected]:" ; \ 
    then                     \ 
       echo "do something" ;               \ 
    fi 

其中

-n --just-print, --dry-run 
    Print the commands that would be executed, but do not execute them. 

-p, --print-data-base 
    Print the data base (rules and variable values) that results from reading 
    the makefiles 

-q, --question 
    Question mode. Do not run any commands, or print anything; just return and 
    exit status that is zero if the specified targets are already up to date, 
    nonzero otherwise. 
相關問題