Supplying Environment Variables to Specific Programs

Learn how to supply environment variables to specific programs.

Perl script

Sometimes, we have a script or program that needs some variables from the environment. Still, we don’t need or want to set these values forever, or we need to override values in our environment temporarily. We can do this by prefixing the command with the variables we need.

To demonstrate this, let’s create a quick Perl script that grabs values from the environment and prints them out. Perl is great for this because it’s already installed on macOS and Ubuntu, and it makes it easy to write a small program to illustrate this concept.

First, we create a file named variables that reads the variables HOME and API_KEY from the environment. We use the cat command to create this file quickly, using the heredoc method we’ve used throughout the course.

The heredoc method uses the << sign after a bash command followed by a delimiter, which terminates the execution.

Perl variables

Variables in Perl start with a dollar sign, and that’s how we get the values of shell and environment variables. That’s why we’ve been placing single quotes around EOF when we’ve used cat to create files. Doing this instructs Bash to treat the contents of the heredoc literally rather than expanding the variables into their values.

Let’s execute this command to create the script:

$ cat << 'EOF' > variables
> #!/usr/bin/env perl
> $home = $ENV{'HOME'};
> print "Home directory: $home\n";
> $apikey = $ENV{'API_KEY'};
> print "API key: $apikey\n";

We then use chmod +x to make the script executable:

$ chmod +x variables

Now, we run the script. Remember that we have to prefix the script’s name with ./ since it’s in the current working directory:

$ ./variables

Use the terminal below to practice these commands.

Get hands-on with 1200+ tech skills courses.