Should I alphabetically order the flags in a command as good practice?

I know that these two commands do the same thing:

ls -la
ls -al

but I'm wondering if there is any preference between them. Is it better practice to order them in a certain way?


Solution 1:

It does not really matter* unless a command explicitly mentions. I have came across no reference that gave anything like a guideline how to put the options one after another. So I think for the sake of readability the options can be arranged alphabetically.

*There is a very very important cavaet that is if any option needs a filename or any other input right after it you need to put it accordingly.

For example, the -f option of grep takes a file as input to take the pattern to look for from the input file. You need to give the command as e.g.:

grep -cf input.txt file.txt 

If you use it like:

grep -fc input.txt file.txt 

it will fail as it will use c as a file name.

Solution 2:

The POSIX conventions define in Guideline 11 and 12 of the Utility Syntax Guidelines that the order "should not matter" unless it's not documented for the utility itself.

The GNU C Library Reference Manual also honors those POSIX conventions in 25.1.1 Program Argument Syntax Conventions.

But notice, there are several utilities that give in some situations strict orders how to perform the parameters (for example find). From the find manpage:

The -name test comes before the -type test in order to avoid having to call stat(2) on every file.

Sometimes the utility complains about the ordering.

Solution 3:

With ls you can hardly go wrong with ordering of options.

But be mindful though that other commands can have different responses to options depending on the order.

An example is the find command. You will get different results for example between:

  find . -ls -mtime -1 

And

  find . -mtime -1 -ls