5

I am working on an executable program - an application or utility. At some point, I want to introduce a new option (to be considered at run-time rather than build-time); the option may be boolean, having a yes/no, on/off semantic; or it may have multiple values, in which case let us consider its value to be a string (which the app could parse into something else, perhaps).

Now, I can:

  • Read an environment variable from within the program, and invoke it with

    MY_OPTION=value my_program

  • Parse a command-line option in the program, and invoke it with

    my_program --my-option=value

  • Do both, i.e. accept either a command-line option or an environment varialbe (but then be left with the question of priority of one method over the other)

Let's ignore, for the sake of discussion, the question of whether the executalbe can also take a configuration file on the command-line and parse it.

What, in your experience, should this decision dependon? What criteria would you suggest for choosing between these alternatives?

einpoklum
  • 2,752

3 Answers3

11

The decision between command-line option and environment variable should primarily be driven by what is convenient for the end-user of the application and the expected usage patterns of the option.

  • If it is likely that the user wants to pass in a different value each time they use the application, then a command-line option is easiest to use and the the logical choice.
  • If the value will change only sporadically, then you can save the user the retyping effort by using an environment variable (which can be set once and then used in multiple runs of the application).
  • If there is a value that works the majority of the time, but occasionally needs to be overwritten, then it might make sense to offer both the environment variable and the command-line option.

For the sake of argument, I consider a configuration file on the command-line as a convenience method to pass in a bunch of command-line options.

-2

This depends entirely on the context. Environment variables have the huge disadvantage that they are shared between applications. So you add an environment variable, you might affect unrelated applications.

Command line arguments are useful for applications run from the command line, as long as you actually intend to use the possible variations. Don’t know how it works for windows ui applications; for macOS UI applications the developer can build a command line directly into the app (useful for sharing code), but this command line is not changeable by the end user.

gnasher729
  • 49,096
-2

One point not covered in other answers: command line calls leave a trace in your bash history if you don't take care to avoid it. So a password passed as a param to a CLI becomes trivially visible after shuffling through CTRL+R. (I'm assuming bash here, but it's generally relevant for most shells)