Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variables with executing a command with exec

Tags:

syntax

bash

exec

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?

like image 423
Ken Avatar asked Apr 04 '14 17:04

Ken


People also ask

How do you execute a command in a variable?

Here, the first line of the script i.e. “#!/bin/bash” shows that this file is in fact a Bash file. Then we have created a variable named “test” and have assigned it the value “$(echo “Hi there!”)”. Whenever you want to store the command in a variable, you have to type that command preceded by a “$” symbol.

How do I assign a variable to the command line?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").

How do I run a command in a bash variable?

Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.

How do I set environment variables in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.


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

From man env:

   env - run a program in a modified environment 
like image 51
devnull Avatar answered Oct 11 '22 07:10

devnull