# Envsh
A Python library for loading environment variables from shell scripts with **variable interpolation** and type-safe reading capabilities.
## Key Advantage: Variable Interpolation
Unlike traditional `.env` files, **envsh uses shell scripts** which support full variable interpolation, calculations, and dynamic configurations:
```bash
# ❌ This WON'T work in .env files:
DATABASE_URL=postgresql://$HOST:5432/$DB_NAME
WORKER_PORTS=$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))
# ✅ This WORKS with envsh (.sh files):
export HOST="localhost"
export DB_NAME="myapp"
export BASE_PORT=8000
export DATABASE_URL="postgresql://$HOST:5432/$DB_NAME"
export WORKER_PORTS="$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))"
export CONFIG_ARRAY="value1,$HOST,value3,port-$BASE_PORT"
```
## Features
- **Variable Interpolation**: Use `$VAR` and `${VAR}` syntax like in shell scripts
- **Shell Calculations**: Support for `$((...))` arithmetic and `$(command)` execution
- **Type-safe Reading**: Convert to `int`, `float`, `str`, `list[int]`, `list[str]` with validation
- **Smart Array Parsing**: Comma-separated values with automatic trimming
- **Multi-directory Search**: Load from multiple directories automatically
- **Error Handling**: Clear error messages for debugging
## Installation
```bash
pip install envsh
```
## Quick Start: Variable Interpolation
1. Create a shell script with interpolated variables:
```bash
# config.sh
export HOST="localhost"
export BASE_PORT=8000
export DB_NAME="myapp"
# Variable interpolation - the main advantage!
export DATABASE_URL="postgresql://$HOST:5432/$DB_NAME"
export API_ENDPOINT="http://$HOST:$BASE_PORT/api"
export WORKER_PORTS="$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))"
export SERVICE_URLS="http://$HOST:$BASE_PORT,https://$HOST:8443"
```
2. Load and use with type safety:
```python
import envsh
# Load environment variables with interpolation
envsh.load()
# Read interpolated values
database_url = envsh.read_env('DATABASE_URL', str)
# Result: "postgresql://localhost:5432/myapp"
worker_ports = envsh.read_env('WORKER_PORTS', list[int])
# Result: [8000, 8001, 8002] - calculated from BASE_PORT!
service_urls = envsh.read_env('SERVICE_URLS', list[str])
# Result: ["http://localhost:8000", "https://localhost:8443"]
```
## Comparison with .env Files
| Feature | `.env` files | `envsh` (shell scripts) |
|---------|-------------|-------------------------|
| Variable interpolation | ❌ No | ✅ Full support |
| Calculations | ❌ No | ✅ `$(($VAR + 1))` |
| Command execution | ❌ No | ✅ `$(date)`, `$(nproc)` |
| Dynamic arrays | ❌ No | ✅ `"$VAR1,$VAR2,suffix"` |
| Type safety | ❌ Strings only | ✅ int, float, str, list[int], list[str] |
| Array parsing | ❌ Manual | ✅ Automatic comma-split |
## API Reference
### `load(search_paths=None, verbose=False)`
Loads environment variables from `.sh` files in the specified directories.
**Parameters:**
- `search_paths` (list[str], optional): Directories to search for `.sh` files. Defaults to `['.', '..']`
- `verbose` (bool, optional): Print information about loaded files. Defaults to `False`
**Example:**
```python
# Load from current and parent directory
envsh.load()
# Load from specific directories
envsh.load(['./config', './env'], verbose=True)
```
### `read_env(name, return_type)`
Reads an environment variable with the specified type.
**Parameters:**
- `name` (str): Name of the environment variable
- `return_type` (Type): Expected return type (`int`, `float`, `str`, `list[int]`, or `list[str]`)
**Returns:**
- The environment variable value converted to the specified type
**Raises:**
- `EnvironmentError`: If the environment variable is not set
- `ValueError`: If the value cannot be converted to the specified type
- `TypeError`: If the return type is not supported
**Examples:**
```python
# Read as integer
port = envsh.read_env('PORT', int)
# Read as string
host = envsh.read_env('HOST', str)
# Read as integer array (comma-separated)
ports = envsh.read_env('PORTS', list[int]) # "8000,8001,8002" -> [8000, 8001, 8002]
# Read as string array (comma-separated)
hosts = envsh.read_env('HOSTS', list[str]) # "localhost,example.com" -> ["localhost", "example.com"]
```
## Variable Interpolation Examples
### Basic Interpolation
```bash
export HOST="localhost"
export PORT=8000
export API_URL="http://$HOST:$PORT/api" # → "http://localhost:8000/api"
```
### Arrays with Interpolation
```bash
export BASE_PORT=8000
export SERVICES="web:$BASE_PORT,api:$(($BASE_PORT + 1)),ws:$(($BASE_PORT + 2))"
# → ["web:8000", "api:8001", "ws:8002"]
```
### Dynamic Configuration
```bash
export ENV="production"
export LOG_LEVEL="INFO"
export CONFIG_NAME="app-$ENV-$(date +%Y%m%d)" # → "app-production-20250811"
export WORKER_COUNT=$(nproc) # → Number of CPU cores
```
## Error Handling
The library provides clear error messages for common issues:
```python
# Missing environment variable
try:
value = envsh.read_env('MISSING_VAR', str)
except EnvironmentError as e:
print(f"Variable not found: {e}")
# Invalid integer conversion
os.environ['INVALID_NUMBER'] = 'not_a_number'
try:
number = envsh.read_env('INVALID_NUMBER', int)
except ValueError as e:
print(f"Conversion error: {e}")
# Unsupported type
try:
value = envsh.read_env('SOME_VAR', dict)
except TypeError as e:
print(f"Type error: {e}")
```
## Use Cases
- **Configuration Management**: Load application configuration from shell scripts
- **Development Environments**: Share environment setup across team members
- **CI/CD Pipelines**: Load environment-specific variables from shell scripts
- **Docker Deployments**: Initialize container environments from shell scripts
## Requirements
- Python 3.7+
- Unix-like system with Bash (Linux, macOS)
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": "https://github.com/TsybulkaM/envsh",
"name": "envsh",
"maintainer": "Envsh Contributors",
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": "environment, variables, shell, bash, configuration, env",
"author": "Envsh Contributors",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/4b/1c/208bccee81437bfca499d440b1bcf9db07eed5cafd155b7194e7285837c5/envsh-0.1.0.tar.gz",
"platform": null,
"description": "# Envsh\n\nA Python library for loading environment variables from shell scripts with **variable interpolation** and type-safe reading capabilities.\n\n## Key Advantage: Variable Interpolation\n\nUnlike traditional `.env` files, **envsh uses shell scripts** which support full variable interpolation, calculations, and dynamic configurations:\n\n```bash\n# \u274c This WON'T work in .env files:\nDATABASE_URL=postgresql://$HOST:5432/$DB_NAME\nWORKER_PORTS=$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))\n\n# \u2705 This WORKS with envsh (.sh files):\nexport HOST=\"localhost\" \nexport DB_NAME=\"myapp\"\nexport BASE_PORT=8000\n\nexport DATABASE_URL=\"postgresql://$HOST:5432/$DB_NAME\"\nexport WORKER_PORTS=\"$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))\"\nexport CONFIG_ARRAY=\"value1,$HOST,value3,port-$BASE_PORT\"\n```\n\n## Features\n\n- **Variable Interpolation**: Use `$VAR` and `${VAR}` syntax like in shell scripts\n- **Shell Calculations**: Support for `$((...))` arithmetic and `$(command)` execution\n- **Type-safe Reading**: Convert to `int`, `float`, `str`, `list[int]`, `list[str]` with validation\n- **Smart Array Parsing**: Comma-separated values with automatic trimming\n- **Multi-directory Search**: Load from multiple directories automatically\n- **Error Handling**: Clear error messages for debugging\n\n## Installation\n\n```bash\npip install envsh\n```\n\n## Quick Start: Variable Interpolation\n\n1. Create a shell script with interpolated variables:\n\n```bash\n# config.sh\nexport HOST=\"localhost\"\nexport BASE_PORT=8000\nexport DB_NAME=\"myapp\"\n\n# Variable interpolation - the main advantage!\nexport DATABASE_URL=\"postgresql://$HOST:5432/$DB_NAME\"\nexport API_ENDPOINT=\"http://$HOST:$BASE_PORT/api\"\nexport WORKER_PORTS=\"$BASE_PORT,$(($BASE_PORT + 1)),$(($BASE_PORT + 2))\"\nexport SERVICE_URLS=\"http://$HOST:$BASE_PORT,https://$HOST:8443\"\n```\n\n2. Load and use with type safety:\n\n```python\nimport envsh\n\n# Load environment variables with interpolation\nenvsh.load()\n\n# Read interpolated values\ndatabase_url = envsh.read_env('DATABASE_URL', str)\n# Result: \"postgresql://localhost:5432/myapp\"\n\nworker_ports = envsh.read_env('WORKER_PORTS', list[int]) \n# Result: [8000, 8001, 8002] - calculated from BASE_PORT!\n\nservice_urls = envsh.read_env('SERVICE_URLS', list[str])\n# Result: [\"http://localhost:8000\", \"https://localhost:8443\"]\n```\n\n## Comparison with .env Files\n\n| Feature | `.env` files | `envsh` (shell scripts) |\n|---------|-------------|-------------------------|\n| Variable interpolation | \u274c No | \u2705 Full support |\n| Calculations | \u274c No | \u2705 `$(($VAR + 1))` |\n| Command execution | \u274c No | \u2705 `$(date)`, `$(nproc)` |\n| Dynamic arrays | \u274c No | \u2705 `\"$VAR1,$VAR2,suffix\"` |\n| Type safety | \u274c Strings only | \u2705 int, float, str, list[int], list[str] |\n| Array parsing | \u274c Manual | \u2705 Automatic comma-split |\n\n## API Reference\n\n### `load(search_paths=None, verbose=False)`\n\nLoads environment variables from `.sh` files in the specified directories.\n\n**Parameters:**\n- `search_paths` (list[str], optional): Directories to search for `.sh` files. Defaults to `['.', '..']`\n- `verbose` (bool, optional): Print information about loaded files. Defaults to `False`\n\n**Example:**\n```python\n# Load from current and parent directory\nenvsh.load()\n\n# Load from specific directories\nenvsh.load(['./config', './env'], verbose=True)\n```\n\n### `read_env(name, return_type)`\n\nReads an environment variable with the specified type.\n\n**Parameters:**\n- `name` (str): Name of the environment variable\n- `return_type` (Type): Expected return type (`int`, `float`, `str`, `list[int]`, or `list[str]`)\n\n**Returns:**\n- The environment variable value converted to the specified type\n\n**Raises:**\n- `EnvironmentError`: If the environment variable is not set\n- `ValueError`: If the value cannot be converted to the specified type\n- `TypeError`: If the return type is not supported\n\n**Examples:**\n```python\n# Read as integer\nport = envsh.read_env('PORT', int)\n\n# Read as string\nhost = envsh.read_env('HOST', str)\n\n# Read as integer array (comma-separated)\nports = envsh.read_env('PORTS', list[int]) # \"8000,8001,8002\" -> [8000, 8001, 8002]\n\n# Read as string array (comma-separated)\nhosts = envsh.read_env('HOSTS', list[str]) # \"localhost,example.com\" -> [\"localhost\", \"example.com\"]\n```\n\n## Variable Interpolation Examples\n\n### Basic Interpolation\n```bash\nexport HOST=\"localhost\"\nexport PORT=8000\nexport API_URL=\"http://$HOST:$PORT/api\" # \u2192 \"http://localhost:8000/api\"\n```\n\n### Arrays with Interpolation\n```bash\nexport BASE_PORT=8000\nexport SERVICES=\"web:$BASE_PORT,api:$(($BASE_PORT + 1)),ws:$(($BASE_PORT + 2))\"\n# \u2192 [\"web:8000\", \"api:8001\", \"ws:8002\"]\n```\n\n### Dynamic Configuration\n```bash\nexport ENV=\"production\"\nexport LOG_LEVEL=\"INFO\"\nexport CONFIG_NAME=\"app-$ENV-$(date +%Y%m%d)\" # \u2192 \"app-production-20250811\"\nexport WORKER_COUNT=$(nproc) # \u2192 Number of CPU cores\n```\n\n## Error Handling\n\nThe library provides clear error messages for common issues:\n\n```python\n# Missing environment variable\ntry:\n value = envsh.read_env('MISSING_VAR', str)\nexcept EnvironmentError as e:\n print(f\"Variable not found: {e}\")\n\n# Invalid integer conversion\nos.environ['INVALID_NUMBER'] = 'not_a_number'\ntry:\n number = envsh.read_env('INVALID_NUMBER', int)\nexcept ValueError as e:\n print(f\"Conversion error: {e}\")\n\n# Unsupported type\ntry:\n value = envsh.read_env('SOME_VAR', dict)\nexcept TypeError as e:\n print(f\"Type error: {e}\")\n```\n\n## Use Cases\n\n- **Configuration Management**: Load application configuration from shell scripts\n- **Development Environments**: Share environment setup across team members\n- **CI/CD Pipelines**: Load environment-specific variables from shell scripts\n- **Docker Deployments**: Initialize container environments from shell scripts\n\n## Requirements\n\n- Python 3.7+\n- Unix-like system with Bash (Linux, macOS)\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A Python library for loading environment variables from shell scripts with type-safe reading capabilities",
"version": "0.1.0",
"project_urls": {
"Bug Reports": "https://github.com/TsybulkaM/envsh/issues",
"Documentation": "https://github.com/TsybulkaM/envsh#readme",
"Homepage": "https://github.com/TsybulkaM/envsh",
"Source": "https://github.com/TsybulkaM/envsh"
},
"split_keywords": [
"environment",
" variables",
" shell",
" bash",
" configuration",
" env"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1ce8e724381925284a719de3e87da33cd5516008c60987f2d0cdf85e313ca463",
"md5": "24afe185d5c073961dbade7179351f7b",
"sha256": "2d56ab50f7268482fb5527c5f463ce8363a590b1f520780200b1fc5dc3bc26f6"
},
"downloads": -1,
"filename": "envsh-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "24afe185d5c073961dbade7179351f7b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 6704,
"upload_time": "2025-08-11T15:20:49",
"upload_time_iso_8601": "2025-08-11T15:20:49.180170Z",
"url": "https://files.pythonhosted.org/packages/1c/e8/e724381925284a719de3e87da33cd5516008c60987f2d0cdf85e313ca463/envsh-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "4b1c208bccee81437bfca499d440b1bcf9db07eed5cafd155b7194e7285837c5",
"md5": "fdf623896d5a1f0b22bc3a3c870b4f1d",
"sha256": "ab32a4652d3d9f662823567e802ab0cf080afab931b171438cfdf78439da4f81"
},
"downloads": -1,
"filename": "envsh-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "fdf623896d5a1f0b22bc3a3c870b4f1d",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 8168,
"upload_time": "2025-08-11T15:20:50",
"upload_time_iso_8601": "2025-08-11T15:20:50.663344Z",
"url": "https://files.pythonhosted.org/packages/4b/1c/208bccee81437bfca499d440b1bcf9db07eed5cafd155b7194e7285837c5/envsh-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-11 15:20:50",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "TsybulkaM",
"github_project": "envsh",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "envsh"
}