2012-10-17 35 views
1

我在我需要創建一個UNIX使用殼叉賦值()。我已經正確地工作了。現在我需要檢查用戶輸入以查看它是否是有效的unix命令。如果它無效(即它的「1035813」),我需要告訴用戶輸入一個有效的命令。Unix外殼:我該如何檢查用戶輸入的,看它是否是一個有效的unix命令?

有沒有一種方法,我可以得到一切可能的UNIX命令的列表,以便我可以在這個列表中的每個字符串比較用戶輸入?還是有更簡單的方法來做到這一點?

+3

你怎麼知道有沒有命令在某些UNIX系統上命名爲「1035813」? – maerics

回答

3

適當的方式做到這一點是:如果

  1. 檢查它是一個內置在你的shell命令。例如,cd應該可能是內置命令。
  2. fork並嘗試exec它。 (execvp可能是你真正想要的,實際上)。如果失敗,請檢查errno以確定原因。

例子:

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 

int main(int argc, char* argv[]) 
{ 
    if (argc != 2) { 
    printf("usage: %s <program-to-run>\n", argv[0]); 
    return -1; 
    } 

    char* program  = argv[1]; 
    /* in this case we aren't passing any arguments to the program */ 
    char* const args[] = { program, NULL }; 

    printf("trying to run %s...\n", program); 

    pid_t pid = fork(); 

    if (pid == -1) { 
    perror("failed to fork"); 
    return -1; 
    } 

    if (pid == 0) { 
    /* child */ 
    if (execvp(program, args) == -1) { 
     /* here errno is set. You can retrieve a message with either 
     * perror() or strerror() 
     */ 
     perror(program); 
     return -1; 
    } 
    } else { 
    /* parent */ 
    int status; 
    waitpid(pid, &status, 0); 
    printf("%s exited with status %d\n", program, WEXITSTATUS(status)); 
    } 

} 
+0

添加perror(程序)到我的execvp解決了我的問題。謝謝! – user1754045

0

嘗試。

if which $COMMAND 
    then echo "Valid Unix Command" 
else 
    echo "Non valid Unix Command" 
fi 
3

您可以檢查which的輸出。如果它不與which: no <1035813> in blah/blah開始那麼它可能不會在該系統上的命令。

0

如果你想找到答案,無論是內置命令,你可以濫用的幫助:

if help $COMMAND >/dev/null || which $COMMAND >/dev/null 
    then echo "Valid Unix Command" 
else 
    echo "Not a valid command" 
fi 
相關問題