Don't Use Hyphens in Environmental Variables
tl;dr: As the title says, don’t use hyphens in environment variables, use underscores instead.
A large part of my job is working on CI pipelines and the automation of the build and deployment of software. This means that I spend a lot of time working with environment variables and the configuration of the tools that I use.
Over the last 24 hours, I’ve spent about 6 of them trying to find out why a bash script I was working on was failing to reconcile the value of a variable. Initially I thought it was to do with the way I was referencing the variable as I was trying to get the name of the variable by partially constructing it with another variable.
Here’s an example of what I mean:
```bash
#!/bin/bash
export user="dave"
export dev-password="apples"
export prod-password="oranges"
current_env="dev"
password_var="${current_env}-password"
password="${!password_var}"
echo $password
```
Note the use of the ${!password_var}
syntax to get the value of the variable whose name is stored in the password_var
variable, essentially doing a double lookup. This is a useful trick to know about and I’ve used it effectively in the past.
However as I was using this within a CI tool’s context, I didn’t know if there was an obscurity that I was simply unaware of because this was not working for me, in particular I was getting an error along the lines of dev-password is not a valid identifier
.
After a lot of searching and trying different things, I eventually found the answer in a StackOverflow post that was talking about the use of hyphens in variable names. Essentially, the hyphen is a valid character in a variable name but it is also a valid character in a command line argument. So when the shell is trying to parse the command, it is getting confused and trying to interpret the hyphen as a command line argument.
The solution is to use underscores instead of hyphens in your variable names. This is a convention that I’ve seen used in a lot of places but I never really understood why. Now I know.