Why does cat not use options the way I expect UNIX programs to use switches?

4

I have been a UNIX user for more years than I care to think about, and in that time I have been trained to expect that when contradictory switches are given to a program the last one wins. Recently I have noticed that

cat -bn file

and

cat -nb file

both use the -b option (number non-blank lines) over the -n option (number all lines). I get this behavior on both BSD and Linux, so I don't think it is an implementation quirk. Is this something that is specified somewhere and am I just crazy for expecting the first example to number all lines?

Chas. Owens

Posted 2010-06-09T11:55:17.740

Reputation: 1 842

You say that -b numbers blank lines. It actually causes non-blank lines to be numbered according to every man page I looked at (Ubuntu/GNU, FreeBSD, HP/UX). – Paused until further notice. – 2010-06-10T05:51:58.557

@Dennis Williamson, yes, you are correct, that is a typo. – Chas. Owens – 2010-06-10T20:49:10.213

Answers

5

I took a look at the FreeBSD source code for cat(1), and the relevant source lines are:

case 'b':
    bflag = nflag = 1;  /* -b implies -n */

So this looks like a deliberate design decision; the interpretation of -b is that it modifies the behavior of -n, rather than -b and -n being two mutually exclusive alternatives.

coneslayer

Posted 2010-06-09T11:55:17.740

Reputation: 7 494

That is an odd decision because they are documented to behave differently (number all lines vs number blank lines). If -n were documented to "number lines" without the word "all", I would agree with the code. Hmm, but looking at the BSD manpage it says "Number the output lines, starting at 1", so this is really just a problem with GNU cat's documentation. – Chas. Owens – 2010-06-09T12:57:23.120

1

Most system commands use C standard library getopt(3) or some variation, and parse the options from left to right. So, as you observed, last one wins.

kmarsh

Posted 2010-06-09T11:55:17.740

Reputation: 4 632

That's the behavior he expects, but in the case he's asking about, the last one doesn't win. – coneslayer – 2010-06-09T12:44:45.037

You already covered that. I was explaining why the usual mechanism usually favors rightmost arguments. – kmarsh – 2010-06-09T14:43:00.217