Understanding Environment Variables
An environment variable is a dynamic value stored in your shell that can affect how running processes behave. For example, the environment variableHISTSIZE (as seen below) controls the maximum number of commands Bash will remember in its history.
To display your current user’s environment variables, run:
Using Environment Variables on the Command Line
Environment variables can be referenced directly in commands. Many applications use theHOME variable to locate a user’s home directory. You can verify this usage with the following commands:
$), the shell substitutes it with its current value. This feature is particularly beneficial for scripting.
Dynamically Incorporating Environment Variables in Scripts
Environment variables allow scripts to adapt to the user running them. For instance, when saving a file to the user’s home directory, using$HOME ensures the path is correctly set without hardcoding it. Consider this example:
/home/aaron/saved_file; if Jane runs it, her file will be created in /home/jane/saved_file. This dynamic adjustment is one of the key benefits of using environment variables.
If you want users to maintain personalized environment variables, you can modify their
.bashrc file. However, for system-wide settings that affect all users, update the /etc/environment file.Configuring Environment Variables
To set a personal environment variable, you can modify your.bashrc file. For system-wide changes that affect all users, edit the configuration file located at /etc/environment.
First, inspect your .bashrc file:
/etc/environment will be applied to every user at their next login. To test your modifications on a virtual machine or similar environment, log out and log back in, then print the environment variable to verify that it has been set correctly.
Running Commands at User Login
While/etc/environment is ideal for setting static environment variables, executing complex commands upon user login requires using the special directory /etc/profile.d. Files in this directory are automatically executed by the login shell.
For example, to log each user’s login date and time, create a script named lastlogin.sh in /etc/profile.d:
#!/bin/bash) because the system processes these files with the current shell.
After logging out and back in, verify the script’s effect by checking the contents of the generated file:
$HOME ensures that the login time is logged in the appropriate user’s home directory.
Conclusion
By managing system-wide environment profiles with files such as/etc/environment and /etc/profile.d, you can effectively configure and customize the behavior of both the shell and various applications across all users on your system. For more in-depth guides, check out our Linux Environment Variables documentation.
Happy configuring!