如何在不考虑空格的情况下运行bash命令

时间:2018-10-16 17:40:58

标签: c bash shell space

我正在使用系统命令来编写C程序。我已将其配置为sh -c。这不适用于带空格的命令。是否有一条命令可以在外壳程序上运行带空格的命令,而不管它是否有空格。我目前正在使用sh -c命令,如下所示:

char s[500];
  strcpy (s, "sh -c");
  strcat (s, i);
  system (s);

1 个答案:

答案 0 :(得分:2)

system(str) 总是调用sh -c "$str"。就是这样。

您在这里所做的是sh -c "sh -c$str"。在这种情况下,为什么要打破这一点应该很明显。

此外,sh并不是bash -在许多操作系统上,它是完全不同的shell,例如ashdash,甚至是bash提供的shell软件包,以sh名称调用时,它以POSIX兼容模式运行,具有不同的功能。


如果要从C程序中调用bash,请不要使用system()

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

/* Here's our actual shell script.
 * Note that it's a constant string; this is CRITICAL for security.
 * Do not UNDER ANY CIRCUMSTANCES concatenate untrusted data with this string; instead,
 * use placeholders ($1, $2, etc) to pull in other data.
 */
const char* bash_script = "printf '%s\n' \"First argument: $1\" \"Second argument: $2\"";

int main(void) {

    int pid = fork();                /* if we didn't fork, execlp() would end our program */
    if (pid == 0) {                  /* if we're the child process fork() created...      */
        execlp("bash",                    /* command to invoke; in exec*p, found in PATH  */
               "bash", "-c", bash_script, /* actually running bash with our script        */
               "bash",                    /* $0 for the script is "bash"; "_" also common */
               "Argument One",            /* $1 for the script                            */
               "Argument Two",            /* $2 for the script                            */
               NULL                       /* NUL terminator for argument list             */
        );
    } else {
        int exit=0;
        waitpid(pid, &exit, 0);
        printf("Shell exited with status: %d\n", exit);
    }
}

您可以在https://ideone.com/UXxH02上看到它运行

相关问题