What is the correct order for placing flags and parameters in a CLI program [closed]
Matthew Harrington
I have noticed that some programs work differently when the flags are used before the input parameters, rather than adding the flags at the end. So I want to know, what is the conventionally accepted way to order parameters and flags in an Ubuntu CLI program.
I'm specifically asking about Ubuntu as this is my platform of concern. I understand that this depends on the program being run, but what is the norm?
Eg:
./myprog -d file.txtVs
./myprog file.txt -d 1 3 Answers
There is no correct order, as it varies from program to program. The OS just hands the command line arguments over to the program in the order they are given. The way in which they are parsed depends on the program or the parsing libraries that are used.
In most cases the order doesn't matter and common parsing libraries like getopt or Python's argparse allow order independent parsing. But other programs can be more picky. Also note that even with order independent parsing you still have order depended arguments. Meaning some options must be follow by a argument:
ls --sort time -lThe time here is an argument to the --sort option and thus must come after it. However the order of --sort time and -l doesn't matter. Many programs allow writing --sort=time to make this more explicit, but not all do.
The GNU project does have a coding standard for command line handling and most of their tools follow that, but it's not something you can depend on.
In cases where order does matter, you generally do ./myprog -d file.txt and it looks nicer in shell scripts as well. The ./myprog file.txt -d style of writing is more for the command line when you just typed the thing and want to add a -d flag, but not cursor all the way back to the middle of the line.
As far as I've seen there is no convention. If you are developing a program/script it is up to you to decide how the order should be handled. For instance, find command will issue a warning if I place argument related to directory after argument related to naming.
$ find /etc -iname "passwd" -maxdepth 1
find: warning: you have specified the -maxdepth option after a non-option argument -iname, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it). Please specify options before other arguments.
/etc/passwdOther programs might not care about the order. I've a simple getopts.sh script which I keep for when i need to use command line arguments in another script, and it parses arguments in no particular order
$ getopts.sh test1 -w1 test2
Hello, I'm main
The arguments are test1 -w1 test2 POSIX conventions and recommendations are that options (things with -) precede arguments/operands (everything else). It's the safest assumption.