SPlatten SPlatten - 10 months ago 51
Linux Question

Linux environment variables referencing other variables

I am using a boot script from a network vendor, I am using this on RedHat 7.2 The start script sets up the environment with several variables, however I don't think these variables are set-up correctly.

I have added the start-up script to /etc/environment and I can see that the variables are defined and available to all users.

This is an example of how the variables are defined in the script:

export V1=/opt/nameofsupplier/sdk/CentOS-RHEL-7-x86_64
export V2=${V1}/lib/cam

There are many more, if I try this from a terminal:

cd $V1

It works fine, however if I try:

cd $V2

I get:

base: cd $V1/lib/cam: No such file or directory

The path is valid, and if I do this in the shell:

export V2=${V1}/lib/cam
cd $V2

It works without any error, how do I fix the script?


You may be right in suspecting an ill-definition of these variables.
/etc/environment can only contain variable definitions - it is not executed like a normal script (see its documentation here, which says Variable expansion does not work in /etc/environment.), so no variable expansion of V1 in the definition of V2 takes place. Therefore V2 is not correctly defined.

Try to source /etc/environment lines in the system-wide /etc/profile (or its equivalent, depending on the shells of your users) or to specific users' ~/.profiles.

As the last resort you can just plain copy the respective lines of /etc/environment to the above mentioned scripts (but this will make them harder to maintain).

You could also correct the definitions in /etc/environment not to rely on expansion, i.e. like this:

export V2=/opt/nameofsupplier/sdk/CentOS-RHEL-7-x86_64/lib/cam

(assuming there are not too much of them to be corrected). But this will also be hard to maintain.