Changing environment variables in a shell script?

Magnus Therning magnus at therning.org
Fri Apr 29 06:59:57 UTC 2005


On Thu, Apr 28, 2005 at 08:55:49PM -0400, Eric Dunbar wrote:
>On 4/28/05, Magnus Therning <magnus at therning.org> wrote:
>> On Thu, Apr 28, 2005 at 01:03:14PM -0700, Chuk Goodin wrote:
>> >I'd like to change an environment variable by running a script and then have
>> >it stay changed after the script has stopped running. My script is very
>> >simple:
>> >
>> >#!/bin/bash
>> >DISPLAY=opal:1
>> >export DISPLAY
>> >
>> >After running it, my DISPLAY variable is unchanged. If I just type the
>> >last two lines (one at a time) into the command prompt, it works. Also,
>> >if I check the DISPLAY variable from within the script, it shows up as
>> >what I want it to be. How do I get it to change my "main" environment
>> >variable?
>> 
>> You can do what you want by 'sourcing' your script:
>> 
>>  $ source script
>> 
>> or
>> 
>>  $ . script
>> 
>> Executing the script starts a new shell and your script is run inside it
>> leaving the environment of the original shell untouched. This beahviour
>> is different from MS-DOS.
>
>Where does one insert this $ source script?

Hmm, I'm not sure what you mean here.

First a clarification. You don't actually type the '$', I put it in the
examples above to signal that it's something you type at the command
line. It's pretty common to write it that way.

If you want the variable set in every shell you start you can source
your script from one of the scripts that your shell sources at startup
(~/.bashrc is a good candidate for bash). Read the man page for more
info on the startup procedure of your shell.

/M

-- 
Magnus Therning                    (OpenPGP: 0xAB4DFBA4)
magnus at therning.org
http://magnus.therning.org/

Software is not manufactured, it is something you write and publish.
Keep Europe free from software patents, we do not want censorship
by patent law on written works.

Never be afraid to try something new. Remember, amateurs built the
ark; professionals built the Titanic.
     -- Anonymous
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
URL: <https://lists.ubuntu.com/archives/ubuntu-users/attachments/20050429/b01e3e68/attachment.sig>


More information about the ubuntu-users mailing list