Parsing of command line options

command lineoptions

For I school project, I have to implement a shell/terminal app. But I am wondering how are command line options parsed, because it appears abit weird to be. For example for the command paste (and I believe other utilities behave similarly)

[jiewmeng@JM tmp]$ paste --help
Usage: paste [OPTION]... [FILE]...

Behavior when combining multiple options into one

[jiewmeng@JM tmp]$ paste -ds file1
file1 xxx
file1
d aaws dafd a

Here it appears options are just ignored …

[jiewmeng@JM tmp]$ paste -sd file1

It behaves the same as paste -, waiting for stdin. But when its valid combination

[jiewmeng@JM tmp]$ paste -sd. file1
file1 xxx.file1.d aaws dafd a

It works. Shouldn't the invalid one give an error instead of waiting for stdin?

[jiewmeng@JM tmp]$ paste -d
paste: option requires an argument -- 'd'
Try 'paste --help' for more information.

Ok, makes sense d requires an argument, but …

[jiewmeng@JM tmp]$ paste -d file1

… waits for stdin. why?

Best Answer

paste -d takes a mandatory argument.

See the man page

     -d, --delimiters=LIST
          reuse characters from LIST instead of TABs

This format really means

     -d LIST or --delimiters=LIST
          reuse characters from LIST instead of TABs

So with paste -d file1, you're setting LIST to file1, and no file name is specified. And as the man page says:

    With no FILE, or when FILE is -, read standard input.

With paste -ds file1, you're setting delimiter to s. You'd have to supply multiple files to see the effect.

Compare

$ paste <(printf 'foo\nbar\n') <(printf 'one\ntwo\n') 
foo<TAB>one
bar<TAB>two
$ paste -ds <(printf 'foo\nbar\n') <(printf 'one\ntwo\n')
foosone
barstwo