Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ Assuming you've installed the command as above and you've got `$GOPATH/bin` in y
godotenv -f /some/path/to/.env some_command with some args
```

If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD`
If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD`.
Optional flag `-s` removes all the loaded files if the command fails and returns the same exit code.

### Writing Env Files

Expand Down
26 changes: 22 additions & 4 deletions cmd/godotenv/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,32 @@ import (
"flag"
"fmt"
"log"

"os"
"os/exec"
"strings"

"github.com/joho/godotenv"
)

func main() {
var showHelp bool
var showHelp, deleteFileOnError bool
flag.BoolVar(&showHelp, "h", false, "show help")
var rawEnvFilenames string
flag.StringVar(&rawEnvFilenames, "f", "", "comma separated paths to .env files")
flag.BoolVar(&deleteFileOnError, "s", false, "delete .env files if the command fails, copy exit status")

flag.Parse()

usage := `
Run a process with an env setup from a .env file

godotenv [-f ENV_FILE_PATHS] COMMAND_ARGS
godotenv [-f ENV_FILE_PATHS] [-s] COMMAND_ARGS

ENV_FILE_PATHS: comma separated paths to .env files
ENV_FILE_PATHS: comma separated paths to .env files (.env is the default)
COMMAND_ARGS: command and args you want to run

-s delete .env files if the command fails, copy exit status

example
godotenv -f /path/to/something/.env,/another/path/.env fortune
`
Expand All @@ -49,6 +53,20 @@ example

err := godotenv.Exec(envFilenames, cmd, cmdArgs)
if err != nil {
if deleteFileOnError {
if len(envFilenames) == 0 {
envFilenames = []string{".env"}
}
for _, filename := range envFilenames {
fileErr := os.Remove(filename)
if fileErr != nil {
log.Println(fileErr)
}
}
if state, ok := err.(*exec.ExitError); ok {
os.Exit(state.ExitCode())
}
}
log.Fatal(err)
}
}