Setting variables using the exec command

You can set a variable for one command as follows:

MY_VARIABLE=my_value ./my_script.sh 

You can pass another script as follows:

 exec ./my_script.sh 

But when I try to do this:

 exec MY_VARIABLE=my_value ./my_script.sh 

I get an error message:

 exec: MY_VARIABLE=my_value: not found 

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

+12
syntax bash exec
source share
2 answers

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 only with the specified variables, use the -i option.

From man env :

  env - run a program in a modified environment 
+32
source share

In bash, you can set environment variables for a command by setting 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 
+5
source share

All Articles