Environment variables work as key-value pairs that are stored in the operating system's environment. Here's how they function:
-
Setting Variables: You can set an environment variable using commands like
exportin Linux. For example:export MY_VAR="Hello, World!" -
Accessing Variables: Once set, you can access the value of an environment variable using commands like
echo:echo $MY_VAR -
Scope: Environment variables can be local to a session or global. Local variables are available only in the current shell session, while global variables can be made persistent by adding them to shell configuration files (e.g.,
.bashrc,.zshrc). -
Using in Programs: Programs can access these variables using system calls or libraries. For example, in Go, you can use
os.Getenvto retrieve the value of an environment variable:value := os.Getenv("MY_VAR") -
Listing Variables: You can list all environment variables using the
envcommand or by accessing them programmatically (e.g.,os.Environ()in Go).
Environment variables are essential for configuring applications and managing system settings dynamically.
