2012-10-17 30 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 
相关问题