Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign default value if env var is empty?

How do you assign a default value if an environment variable isn't set in Go?

In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass') where pass is the default value if MONGO_PASS env var isn't set.

I tried an if statement based on os.Getenv being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.

like image 878
Ryan Clair Avatar asked Oct 30 '16 06:10

Ryan Clair


People also ask

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

How do you assign a default value to a variable in UNIX?

Or to assign default to VARIABLE at the same time: FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.


1 Answers

There's no built-in to fall back to a default value, so you have to do a good old-fashioned if-else.

But you can always create a helper function to make that easier:

func getenv(key, fallback string) string {     value := os.Getenv(key)     if len(value) == 0 {         return fallback     }     return value } 

Note that as @michael-hausenblas pointed out in a comment, keep in mind that if the value of the environment variable is really empty, you will get the fallback value instead.

Even better as @ŁukaszWojciechowski pointed out, using os.LookupEnv:

func getEnv(key, fallback string) string {     if value, ok := os.LookupEnv(key); ok {         return value     }     return fallback } 
like image 73
janos Avatar answered Oct 05 '22 17:10

janos