37

You can set a variable for a single command like this:

MY_VARIABLE=my_value ./my_script.sh

You can hand off to another script like this:

exec ./my_script.sh

But when I try to do both like this:

exec MY_VARIABLE=my_value ./my_script.sh

I get an error:

exec: MY_VARIABLE=my_value: not found

Why is that?
Is there any way to do this?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ken
  • 619
  • 1
  • 7
  • 11

2 Answers2

79

You need to use env to specify the environment variable:

exec env MY_VARIABLE=my_value ./my_script.sh

If you want your script to start with an empty environment or with only the specified variables, use the -i option.

From man env:

   env - run a program in a modified environment
devnull
  • 118,548
  • 33
  • 236
  • 227
17

In bash, you can set environment variables for a command by putting the assignments at the beginning of the command. This works the same for exec as any other command, so you write:

MYVARIABLE=my_value exec ./my_script.sh
rici
  • 234,347
  • 28
  • 237
  • 341
  • 4
    The nice thing about 'exec env' is that you can use it on a variable that may or may not set shell variables. for example if I have a script which does some setup for an arbitrary command, I could end it with `exec env "$@"` and it will work whether or not "$@" sets variables. To use this solution, I'd have to parse and split up the arguments in "$@". – Ken Apr 04 '14 at 18:30