简体   繁体   中英

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?

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 .

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM