How to handle scripts woven from C language to bone shell

Asked 2 years ago, Updated 2 years ago, 101 views

You are about to use bash script in C language. You don't have to run the bash script file

As shown in the source below, I want to define the bash script as a definition statement and then run it in the program itself, but it doesn't work as I thought.

#define RESSHELL "/bin/sh -c '\
OS_CHECK_CMD=uname\r\n\
echo $OS_CHECK_CMD\r\n\
OS_CHECK_CMD_PATH=`command -v $OS_CHECK_CMD`\r\n\
echo $OS_CHECK_CMD_PATH\r\n\
'\
"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define MAXLINE 256

int main()
{
    FILE *fp;
    int state;

    char buff[MAXLINE];
    fp = popen(RESSHELL, "r");

    if (fp == NULL)
    {
        perror("erro : ");
        exit(0);
    }

    while(fgets(buff, MAXLINE, fp) != NULL)
    {
        printf("%s", buff);
    }

    state = pclose(fp);
}

When executing the above code, /usr/bin/uname should be output, but blank is output.

OS_CHECK_CMD_PATH=`command -v $OS_CHECK_CMD`\r\n\

I don't think the result value is saved in OS_CHECK_CMD_PATH here, what should I do?

c preprocessor bash

2022-09-22 19:38

1 Answers

Tested in CENTOS 7.4.

// test.c
#include <stdio.h>
#include <stdlib.h>


#define SHELLSCRIPT "\
#/bin/bash \n\
OS_CHECK_CMD=uname \n\
echo $OS_CHECK_CMD \n\
OS_CHECK_CMD_PATH=\"command -v $OS_CHECK_CMD\" \n\
echo $OS_CHECK_CMD_PATH \n\
"

int main()
{
    system(SHELLSCRIPT);
    return 0;
}

[allinux@lgcare01 ~]$ ./test
uname
command -v uname


2022-09-22 19:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.