Home > Back-end >  How does the two differ: Declaring an environment variable at the same line as the command vs. decla
How does the two differ: Declaring an environment variable at the same line as the command vs. decla

Time:04-13

I have compiled a C program with a shared library. I do not understand why

$ LD_LIBRARY_PATH=<path_to_lib> ./a.out

works; yet

$ LD_LIBRARY_PATH=<path_to_lib>
$ ./a.out

does not.

The two-line approach sometimes worked for me before. So I feel confused.

CodePudding user response:

I'm assuming you meant LD_LIBRARY_PATH, but either way, the answer is the same:

There are two types of variables that are relevant in this context:

  1. Non-environment variables, which are set in the current shell only. Sometimes these are called "shell variables" or "local variables", but those terms can have other meanings.
  2. Environment variables, which are set in the current shell and persist into subshells. They can be displayed with the "env" command.

The first (one line) command in your post sets LD_LIBRARY_PATH as an environment variable, which means that its value persists into subshells. When a.out is invoked, it spawns and runs inside a subshell. When you precede a command with a variable setting on the same command line, the value is only valid for the duration of the command (a.out in this case). After a.out finishes, the value is no longer set.

The second set of commands sets LD_LIBRARY_PATH as a non-environment variable, which means the variable is available in the current shell only. Because a.out runs in a subshell when you call it, it won't see the value of LD_LIBRARY_PATH. You would need to precede the LD_LIBRARY_PATH=<path_to_lib> with an "export" to make it an environment variable, as shown below.

$ cat ./a.out
#!/bin/bash
env | grep LD_LIBRARY_PATH
echo $LD_LIBRARY_PATH

# LD_LIBRARY_PATH is treated as an environment variable
$ LD_LIBRARY_PATH=/usr/lib ./a.out
LD_LIBRARY_PATH=/usr/lib
/usr/lib

# LD_LIBRARY_PATH is NOT set as an environment variable
$ LD_LIBRARY_PATH=/usr/lib
$ ./a.out

# "export" sets LD_LIBRARY_PATH as an environment variable
$ export LD_LIBRARY_PATH
$ ./a.out
LD_LIBRARY_PATH=/usr/lib
/usr/lib
$
  • Related