Unix shell:如何检查用户输入以查看它是否是有效的unix命令?

时间:2012-10-17 17:44:00

标签: c shell unix

我有一个作业,我需要使用fork()创建一个unix shell。我的工作正常。现在我需要检查用户输入以查看它是否是有效的unix命令。如果它无效(即“1035813”),我需要告诉用户输入有效的命令。

有没有办法可以获得每个可能的unix命令的列表,这样我就可以将用户输入与此列表中的每个字符串进行比较?或者有更简单的方法吗?

4 个答案:

答案 0 :(得分:3)

您可以查看which的输出。如果它不以which: no <1035813> in blah/blah开头,那么它可能不是该系统上的命令。

答案 1 :(得分:3)

执行此操作的适当方法是:

  1. 检查它是否是shell中的内置命令。例如,cd应该是内置命令。
  2. fork并尝试exec。 (execvp可能是你真正想要的,实际上)。如果失败,请检查errno以确定原因。
  3. 示例:

    #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));
      }
    
    }
    

答案 2 :(得分:0)

试试吧。

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

答案 3 :(得分:0)

如果你想知道它是否是内置命令,你可以滥用帮助:

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