Bash – Convention personal environment variables

bashenvironment-variables

Is there an Unix convention for setting personal environment variables? I read they should be put in $HOME/.bash_profile instead of $HOME/.bashrc. Nonetheless, I was thinking of providing a way to distinguish my own variables. This way even though I would forget one I could tell at first glance whether it has been set by me or not. For instance when I do the autocompletion in the terminal I could make my variables start with an underscore, or a minus 'm' as in one of C++ language's conventions. I understand there might not be an absolute answer but I'd like to hear about some good practice and conventions that work toward this purpose: providing a simple way to distinguish system environment variables from personal ones.

Best Answer

Where to set environment variables is covered in What's the best distro/shell-agnostic way to set environment variables?

Regarding naming, the main reason to set environment variables is because an application uses them, so you don't get to choose the name.

There is no concept of namespaces for environment variables. The closest thing is to pick a prefix, generally of the form SOMETHING_ (i.e. the prefix ends with an underscore and you have variables SOMETHING_FOO, SOMETHING_BAR, …). But most variables aren't for a specific application, but rather a family of applications. If a variable is only meaningful in one application, it should generally be a command line option. So there isn't much need for namespaces.

If you're defining variables only for use on the command line, then don't use environment variables, use shell variables. (See Difference between environment variables and exported environment variables in bash) If you define a variable in a shell script and you don't use export, that's a shell variable, not an environment variable, and it's only visible in the shell where you defined them. So if you're defining a variable for use on the command line:

  • Define it in your shell interactive startup file (~/.bashrc for bash, ~/.zshrc for zsh, ~/.config/fish/config.fish for fish).
  • Don't export it.
  • There's a widespread convention that environment variables are all-uppercase and shell variables are all-lowercase.

For your own use, pick whatever names you like, as long as they don't conflict with environment variables that you use (environment variables are automatically imported as shell variables). I don't recommend an initial underscore because that's what bash and zsh's completion systems use internally.

Related Question