2014-09-30 57 views
1

我正在爲實現應用程序模板的OCaml庫Gasoline編寫自動化測試。應用將失敗,並在某些情況下在規定的退出代碼,如退出代碼64 EXIT_USAGE當應用程序調用一個不適形成命令行:執行命令並測試其退出狀態的Unix實用程序

% ./punishment.byte -x 
punishment.byte: illegal option -- x 
Usage: punishment.byte [-n number] [-p paragraph] [-c configfile] 
Exit 64 

是否有可用於一個標準的Unix工具運行子命令./punishment.byte -x,如果子命令退出狀態碼64,則退出狀態碼0?像

% expect_status 64 ./punishment.byte -x 
punishment.byte: illegal option -- x 
Usage: punishment.byte [-n number] [-p paragraph] [-c configfile] 
Exit 0 

由於我使用一個Makefile來協調測試的東西,一個清晰的語句,如expect_status 64 ./punishment.byte -x將是不錯的。

  1. 在控制檯交互實施例中的線Exit是資料,而不是輸出的一部分。
  2. 我很清楚,我可以編寫這樣一個工具,以及如何去做,我只是想確保沒有標準命令做到這一點。
+4

我不知道標準實用程序(可能有一個),但shell將最後一個退出代碼存儲在$?中。變量。我想你可以用幾行shell腳本編寫你自己的工具,例如如果[「$?」 -eq「$ expected」]然後退出0 fi。 – bmb 2014-09-30 00:13:16

+3

是的,有一個標準的工具;它被稱爲外殼。 8-)} – 2014-09-30 00:31:46

+0

你可能感興趣的有[GNU Autotest](https://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Using-Autotest.html)。 – 5gon12eder 2014-09-30 01:30:34

回答

2

您的問題的答案是否定的。 * nix系統上沒有標準實用程序來運行命令並根據特定值測試其退出代碼。可能是因爲你自己寫一個很簡單。

我從你的代碼中的%猜測你正在使用zsh。如果你真的使用csh(或tcsh),那麼事情就會有所不同。

這就是說,你可以隨便寫一個外殼函數來做到這一點:

expect_status() { 
    local expected=$1 
    shift 
    "[email protected]" 
    (($? == expected)) 
} 

但將運行當前的shell環境中的命令,這可能有你不想副作用。它可能會更好地實現爲一個腳本 - 只是文件名expect_status保存在某個地方它在你的$ PATH,並給它讀取和執行權限:

#!/bin/bash 
expected=$1 
shift 
"[email protected]" 
(($? == expected)) 

或者避開bash化:

#!/bin/sh 
expected=$1 
shift 
${1+"[email protected]"} 
[ $? -eq $expected ] 
+0

我可以做到這一點,但這並沒有回答這個問題,因爲我要求有一個標準的工具來做這件事! – 2014-09-30 06:05:19

+0

對我來說似乎仍然是最好的答案,謝謝! :) – 2015-04-29 07:15:59

1

如上所述,您可以通過引用shell變量「$?」來檢查最後命令執行的退出代碼。

$ ls -bogusOption   
ls: invalid option -- 'O' 
Try 'ls --help' for more information. 
$ echo $? 
2 

shell可用作測試退出代碼的實用程序。說,

$ cat test.sh 
#!/usr/bin/env bash 

echo "executing bogus option" 
ls -bogusOption 

if [ "$?" -eq "0" ]; then 
    echo "command succeeded." 
else 
    echo "command failed" 
fi 

$ bash -xv ./test.sh 
#!/usr/bin/env bash 

echo "executing bogus option" 
+ echo 'executing bogus option' 
executing bogus option 
ls -bogusOption 
+ ls -bogusOption 
ls: invalid option -- 'O' 
Try 'ls --help' for more information. 

if [ "$?" -eq "0" ]; then 
    echo "command succeeded." 
else 
    echo "command failed" 
fi 
+ '[' 2 -eq 0 ']' 
+ echo 'command failed' 
command failed 
+3

從來沒有任何理由去做'命令;如果[$? -eq 0]'。只要做'如果命令;然後回顯「命令成功」;否則回顯「命令失敗。」; fi'。測試'$?'是* if如何工作*。 – 2014-09-30 01:32:11

0

好在某種意義上,有一個標準的實用程序:外殼本身:

command1 && command2 

上面將只執行command2如果command1退出代碼是0。另外,這樣的:

command1 || command2 

將只運行command2如果command1退出代碼不是0

要在其他的答案中描述檢查特定的退出狀態,你可以使用$?

command; [ "$?" -eq 64 ] && command2 

因此,您正在尋找的功能基本上是直接構建到shell中的,因此,您不會找到設計用於執行此操作的實用程序。

+0

再進一步,你可以'別名'你的命令這樣'別名檢查='[「$?」 -eq 64] && echo beep beep'',然後執行'command; check' – 2014-09-30 12:27:29