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?
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.
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 ").
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With