Performing arithmetics with execve from arguments passed by terminal

47 views Asked by At

Trying to understand how to perform an arithmetic operation from arguments passed from terminal and use them in execve ?

./myProgram 'echo "$1+$2=$(($1+$2))"' 3 5

this is suppose to give me an output of 8

what i've tried manually without argv :

pid_t pid;
char *parmList[] = {"sh", "-c", "echo $0 $1 + $2 1 2", NULL};
char *envParms[3] = {"1=1", "2=2", NULL};

if ((pid = fork()) == -1)
    perror("fork error");
else if (pid == 0)
{
    execve("/bin/sh", parmList, envParms);
    printf("Return not expected. Must be an execve error.n");
}

i get the $0 which is sh ✅

but $1 and $2 are not recognized ...what i am missing ?

1

There are 1 answers

1
William Pursell On BEST ANSWER

You don't want to be passing 1 and 2 in the environment. The shell wants them as positional parameters. So you could do:

char *parmList[] = {"sh", "-c", "echo $0 $1 + $2 1 2", "sh", "1", "2", NULL};