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?

2
  • 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). Jun 10, 2010 at 5:51
  • @Dennis Williamson, yes, you are correct, that is a typo. Jun 10, 2010 at 20:49

2 Answers 2

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.

1
  • 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. Jun 9, 2010 at 12:57
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.

2
  • That's the behavior he expects, but in the case he's asking about, the last one doesn't win.
    – coneslayer
    Jun 9, 2010 at 12:44
  • You already covered that. I was explaining why the usual mechanism usually favors rightmost arguments.
    – kmarsh
    Jun 9, 2010 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.