Environment variables are a fundamental aspect of Unix-like operating systems, including Linux. They allow you to store configuration settings and other important information that can be accessed by scripts, applications, and the operating system itself. This lesson will cover what environment variables are, how to use them, common patterns, and provide a cheat sheet and real-world exercise.
#### What Are Environment Variables?
Environment variables are dynamic values that can affect the way running processes behave on a computer. They are used to pass information into processes that are spawned from the shell or other programs. Some typical uses include:
- Storing system paths
- Setting up application configurations
- Managing user settings
- Passing sensitive data (like API keys or database URLs)
#### Common Environment Variables
Here are some commonly used environment variables in Linux:
- `PATH`: Specifies directories where executable programs are located.
- `HOME`: The home directory of the current user.
- `USER`: The name of the current user.
- `SHELL`: The current user's shell.
- `PWD`: The current working directory.
- `LANG`: The system language and locale settings.
#### Using Environment Variables
##### Setting Environment Variables
You can set environment variables in the shell using the `export` command:
```bash
export VARIABLE_NAME=value
```
Example:
```bash
export DATABASE_URL="postgres://user:password@localhost:5432/mydatabase"
```
This sets the `DATABASE_URL` variable to a PostgreSQL connection string.
##### Accessing Environment Variables
To access the value of an environment variable, use the `
symbol followed by the variable name:
```bash
echo $DATABASE_URL
```
This will output the value of `DATABASE_URL`.
##### Persistent Environment Variables
To make environment variables persistent across sessions, you can add them to your shell's configuration file (e.g., `.bashrc` or `.bash_profile` for Bash users):
```bash
echo 'export DATABASE_URL="postgres://user:password@localhost:5432/mydatabase"' >> ~/.bashrc
```
Then, reload the configuration:
```bash
source ~/.bashrc
```
##### Unsetting Environment Variables
To remove an environment variable, use the `unset` command:
```bash
unset VARIABLE_NAME
```
Example:
```bash
unset DATABASE_URL
```
This will remove the `DATABASE_URL` variable from the environment.
#### Realistic Examples
##### Example 1: API Keys
Suppose you are developing an application that requires access to a third-party API. You can store the API key as an environment variable to keep it secure and easily configurable.
```bash
export API_KEY="your_api_key_here"
```
In your application, you can access this variable using your programming language of choice. For instance, in Python:
```python
import os
api_key = os.getenv("API_KEY")
```
##### Example 2: Database Configuration
A common scenario in web development is setting up database configuration through environment variables. This is especially useful in deployment scenarios where configuration may change between environments (development, staging, production).
```bash
export DATABASE_URL="postgres://user:password@localhost:5432/mydatabase"
```
In a web application (e.g., using Flask in Python):
```python
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
db = SQLAlchemy(app)
```
#### Common Use Patterns
1. **Configuration Management**: Store environment-specific configurations such as database URLs, API keys, and service endpoints.
2. **Sensitive Information**: Keep sensitive information like passwords and tokens out of source code.
3. **Customization**: Allow users to customize the behavior of scripts and applications without modifying the code.
4. **System Settings**: Manage system-wide settings like locale, timezone, and user preferences.
#### Cheat Sheet
- **Set an environment variable**:
```bash
export VARIABLE_NAME=value
```
- **Access an environment variable**:
```bash
echo $VARIABLE_NAME
```
- **Make environment variables persistent**:
Add `export VARIABLE_NAME=value` to `~/.bashrc` or `~/.bash_profile`
- **Remove an environment variable**:
```bash
unset VARIABLE_NAME
```
#### Exercise: Setting Up a Web Application
1. **Set Up Environment Variables**:
- Create a file named `.env` with the following content:
```plaintext
DATABASE_URL="postgres://user:password@localhost:5432/mydatabase"
API_KEY="your_api_key_here"
```
- Source the environment variables:
```bash
export $(grep -v '^#' .env | xargs)
```
2. **Access Environment Variables in a Script**:
- Create a Python script named `app.py`:
```python
import os
database_url = os.getenv('DATABASE_URL')
api_key = os.getenv('API_KEY')
print(f"Database URL: {database_url}")
print(f"API Key: {api_key}")
```
3. **Run the Script**:
```bash
python app.py
```
This will print the values of `DATABASE_URL` and `API_KEY` that you set in the `.env` file.
### Conclusion
Environment variables are a powerful tool for managing configuration and sensitive information in Linux. By understanding how to set, access, and manage these variables, you can enhance the flexibility and security of your applications and scripts. Use the cheat sheet and exercise provided to practice and solidify your understanding of environment variables.