3

I am writing some scripts in bash and other languages and I am always confused (this might be due to different syntax of various tools I have used in the past): what is the most generally accepted syntax for optional command line parameters?

Should I use --my-parameter 10 or -mypar10 or --my-parameter=10 or -mypar=10 or something else?

Valentas
  • 349
  • 2
  • 9

1 Answers1

4

Posix recommends some Program Argument Syntax Conventions:

e.g.:

Option names are single alphanumeric characters

so, for you this means to use:

-p 10

or the equivalent

-p10

(p for my(p)arameter, you could of course use m if you prefer).

GNU adds long options to the convention:

Long options consist of ‘--’ followed by a name made of alphanumeric characters and dashes. Option names are typically one to three words long, with hyphens to separate words

--my-parameter=10

--my-parameter 10, -mypar10 and -mypar=10 are not valid within these conventions.


For shell scripts, you might want to use getopt/getopts to do the parsing and validation for you.

See:

pLumo
  • 22,231
  • 2
  • 41
  • 66
  • 1
    It's probably worth mentioning the shell built-in `getopts`, and `getopt` (on some platforms) to handle long options. See [this](https://stackoverflow.com/a/7948533/2344631) over on StackOverflow – roaima Sep 07 '20 at 07:16