I'm using Ubuntu Natty.
I have a shell script which I have saved to /etc/init.d/qstart. The shell script contains the following:
apt-get -y update
apt-get -y upgrade
apt-get -y install tofrodos gcc make nmap lsof expect sysstat
dbpass="mydbpassword"
However, after I execute the script, I want to test that dbpass is set and I enter echo $dbpass
in the prompt. But it's empty.
How do I define a variable in my shell script so that I can access it outside of it?!
Thanks in advance.
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.
$() – the command substitution. ${} – the parameter substitution/variable expansion.
Variable Scope of Bash FunctionsBy default, every variable has a global scope that means it is visible everywhere in the script. You can also create a variable as a local variable. When you declare a local variable within the function body, it is only visible within that function.
A bash shell script have parameters. These parameters start from $1 to $9. When we pass arguments into the command line interface, a positional parameter is assigned to these arguments through the shell. The first argument is assigned as $1, second argument is assigned as $2 and so on...
You can't set variables in parent process's environment. You can only set your current process's environment or prepare an environment for your process's children.
That said, you can instruct your shell to run commands from a script in the current shell process rather than forking a new shell. You can do it like this:
source your_script.sh
or
. your_script.sh
(note the space after the dot). Since here commands inside your_script.sh
are run by the current shell the changes made to the environment inside the script are retained.
However, if the shell running your script is not an ancestor of the shell in which you wish to use the environment variable then there is no way to achieve your goal using environment variables at all. For example, if you script is run at initialization by some childless shell all environment settings done there are irreversibly lost forever. In this case, use some other mechanism like a file (perhaps somewhere under /var
).
If you want all instances of a given shell to have certain variables set in their environment you can use initialization scripts that most shells use. Usually, they have a system-wide and per-user initialization scripts. For example, bash uses /etc/profile
as system-wide initialization script for interactive login shell and $HOME/.bash_profile
(also $HOME/.bash_login
and $HOME/.profile
) as per-user initialization script. See this reference for bash-specific details. If you use a different shell, try its respective manual.
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