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

Time:04-01

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?

CodePudding user response:

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;

CodePudding user response:

Swap the order of env's arguments. It expects variable assignments (a=11) to precede the command (bash).

name[0]="/usr/bin/env";
name[1]="a=11";
name[2]="bash";
name[3]=NULL;

Per the env(1) man page:

SYNOPSIS
       env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
DESCRIPTION
       Set each NAME to VALUE in the environment and run COMMAND.

CodePudding user response:

The first non-option argument to bash is expected to be the name of a script to execute.

To execute a command using bash, you would use the -c option.

For example, to execute

a=11; printf '%s\n' "$a"

one would use

bash -c 'a=11; printf '\''%s\n'\'' "$a"'

So the C code is

#include <unistd.h>

void main(void) {
    char *name[3];
    name[0] = "bash";
    name[1] = "-c";
    name[2] = "a=11; printf '%s\n' \"$a\"';
    execvpe(name[0], name, NULL);
}

Replaced execve with execvpe to avoid having to use env.

CodePudding user response:

It worked. I wasn't defining a and b before bash, and there was the error. Thank you all!

  • Related