Search code examples
cbashexec

Can't define variables when calling "/usr/bin/env bash" with execve()


I want to execute /usr/bin/env and print out a=11 and b=22. Currently, what I have:

#include <unistd.h>
void main() {
    char *name[3];
    name[0]="/usr/bin/env";
    name[1]="bash";
    name[2]=NULL;
    execve(name[0], name, NULL);
}

I can run it perfectly as it opens a bash shell.

However, I'm trying to define and print a=11 and b=22. When trying to define a=11, I'm doing:

#include <unistd.h>
void main() {
    char *name[4];
    name[0]="/usr/bin/env";
    name[1]="bash";
    name[2]="a=11";
    name[3]=NULL;
    execve(name[0], name, NULL);
}

And it returns this error:

bash: a=11: No such file or directory

What am I doing wrong?


Solution

  • Not sure where are you expecting the variables to be printed, but you need something like this

    name[0]="/usr/bin/env";
    name[1]="a=11";
    name[2]="b=22";
    name[3]="bash";
    name[4]="-c";
    name[5]="printf \"%d %d\\n\" $a $b";
    name[6]=NULL;