- [Narrator] Function to prepend to environment variables.
In the previous video, we've learned how to play
with variables and environment variables.
In this video, we're going to see how to learn to use
a list of paths of where to search
for executables, libraries and so on.
Examples are $PATH, $LD_LIBRARY_PATH,
which will typically look like this.
This essentially means that whenever the shell
has to execute binaries, it'll first
look into /usr/bin followed by /bin.
A very common task that one has to do when building
a program from source and installing to a custom path is
to add its bin directory to the path environment variable.
Let's say in this case we install My App to /opt/myapp,
which has binaries in a directory called "bin"
and libraries in lib.
Let's see how to do it.
A way to do this is to say it as ...
Now, PATH and LD_LIBRARY_PATH
should now look something like this.
However, we can make this easier by adding
this function, .bashrc.
This can be used in the ways it's showing on the screen.
Now we'll see how this function works.
We define a function called "prepend," which first checks
if the directory specified by the second parameter
to the function exists.
If it does, the eval expression sets the variable
with the name in the first parameter equal to
the second parameter's string, followed by ":,"
the path separator, and then the original
value for the variable.
However, there is one caveat.
If the variable is empty when we try to prepend,
there will be a trailing at the end.
To fix this, we can modify the function to look like this.
In this form of the function, we introduce
a shell parameter expansion of the form.
This expands to expression if parameter is set
and is not null.
With this change, we take care to try to append ":"
at the old value if and only if the old value
existed when trying to prepend.
Also, in this video, we successfully learned
about the function to prepend to environment variables.
In the next video, we'll see how to math with the shell.