Exporting Variables

Problem

You defined a variable in one script, but when you called another script it didn’t know about the variable.

Solution

Export variables that you want to pass on to other scripts:

export MYVAR
export NAME=value

Discussion

Sometimes it’s a good thing that one script doesn’t know about the other script’s variables. If you called a shell script from within a for loop in the first script, you wouldn’t want the second script messing up the iterations of your for loop.

But sometimes you do want the information passed along. In those cases, you can export the variable so that its value is passed along to any other program that it invokes.

If you want to see a list of all the exported variables, just type the built-in command env (or export -p) for a list of each variable and its value. All of these are available for your script when it runs. Many have already been set up by the bash startup scripts (see Chapter 16 for more on configuring and customizing bash).

You can have the export statement just name the variable that will be exported. Though the export statement can be put anywhere prior to where you need the value to be exported, script writers often group these export statements together like variable declarations at the front of a script. You can also make the export part of any variable assignment, though that won’t work in old versions of the shell.

Once exported, you can assign repeatedly to the variable without exporting it each time. So, sometimes you’ll see ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.