env
Overview
The env
command displays environment variables or runs a program in a modified environment. It’s essential for managing environment variables and running commands with specific environmental settings.
Syntax
env [options] [name=value...] [command [args...]]
Common Options
Option | Description |
---|---|
-i |
Start with empty environment |
-u name |
Remove variable from environment |
-0 |
End output lines with null character |
--help |
Display help |
--version |
Display version |
Key Use Cases
- Display environment variables
- Run programs with modified environment
- Script environment management
- Debugging environment issues
- Portable script execution
Examples with Explanations
Example 1: Display All Variables
env
Shows all environment variables
Example 2: Run with Clean Environment
env -i /bin/bash
Starts bash with empty environment
Example 3: Set Variable for Command
env PATH=/usr/bin:/bin ls
Runs ls with modified PATH
Example 4: Remove Variable
env -u HOME pwd
Runs pwd without HOME variable
Common Usage Patterns
Check specific variable:
env | grep PATH
Run with additional variable:
env EDITOR=vim crontab -e
Clean environment execution:
env -i PATH=/usr/bin:/bin command
Environment Variables
Common variables: - PATH: Executable search path - HOME: User home directory - USER: Current username - SHELL: Default shell - LANG: Locale setting - PWD: Current directory - EDITOR: Default editor
Performance Analysis
- Very fast operation
- No file system access
- Minimal memory usage
- Good for environment debugging
- Efficient for script execution
Best Practices
- Use for portable scripts
- Clean environment for security
- Document required variables
- Validate environment in scripts
- Use specific paths when needed
Scripting Applications
Portable shebang:
#!/usr/bin/env bash
Environment validation:
if ! env | grep -q "REQUIRED_VAR"; then echo "Missing required environment variable" exit 1 fi
Clean execution:
env -i PATH=/usr/bin:/bin HOME=/tmp command
Security Considerations
- Clean environment for security
- Validate environment variables
- Avoid exposing sensitive data
- Use minimal required environment
- Check for environment injection
Integration Examples
With cron jobs:
0 2 * * * env PATH=/usr/local/bin:/usr/bin:/bin backup.sh
Service execution:
env -i PATH=/usr/bin USER=service /usr/local/bin/service
Development environment:
env NODE_ENV=development npm start
Troubleshooting
- Missing environment variables
- Path resolution issues
- Locale problems
- Permission errors
- Variable inheritance issues