Introduction to with-env
The with-env
command is a powerful tool that allows developers to temporarily set environment variables for the execution of commands. This capability can be immensely useful in various scenarios, such as testing, CI/CD pipelines, and ensuring scripts run with the correct context. In this guide, we will explore a comprehensive list of with-env
APIs along with practical code snippets.
Basic Usage
To set an environment variable for a single command:
with-env VAR_NAME=value command
Multiple Variables
You can set multiple environment variables at once:
with-env VAR1=value1 VAR2=value2 command
Usage in Scripts
with-env
can be particularly useful in scripts. For example, setting variables for a build process:
#!/bin/sh with-env BUILD_ENV=production API_KEY=abcdef123456 ./build.sh
Persisting Variables
Persisting environment variables across multiple commands within a script can be done as follows:
#!/bin/sh export VAR1=value1 export VAR2=value2 with-env VAR1=$VAR1 VAR2=$VAR2 \\
command1 && \\
command2
Integrating with Docker
When working with Docker, with-env
can streamline the process of setting environment variables:
with-env DB_HOST=localhost DB_PORT=5432 \\
docker run -e DB_HOST -e DB_PORT my-docker-image
CI/CD Pipelines
Using with-env
in CI/CD pipelines can ensure that your scripts run with the appropriate context:
stages:
- test
test:
stage: test
script:
- with-env NODE_ENV=test npm test
Practical Application Example
Let’s put together a sample application code that leverages with-env
for setting environment variables and running the application:
#!/bin/sh echo "Starting application with environment variables..." with-env NODE_ENV=production API_URL=https://api.example.com \\
node app.js
This script initializes the application with production settings by temporarily setting the NODE_ENV
and API_URL
variables just for the execution of node app.js
.
With these with-env
commands and use cases, you can significantly enhance the flexibility and reliability of your scripting workflows.
Hash: 9ec2de7f731f9ae5daac00df852479c07ce736b8586b84a09adba83599a365b3