Eric Lagergren
Eric Lagergren

Reputation: 511

What does this shell command do?

I'm re-writing GNU's wc utility in a different language, and I ran across this command which should cause wc to output 0 bytes counted.

(dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group

As I currently understand it, dd is started in a separate (sub) shell, then wc is started, and then the contents of /etc/group are redirected inside the shell?

The dd command uses an input block size of 99kB and skips one of those before reading the input? That's where I get tripped up.

Right now my version reports ~980 bytes read, so I'd like to better understand this command so my utility can reflect that.

Upvotes: 4

Views: 106

Answers (3)

clt60
clt60

Reputation: 63892

Beware, it depends of the implementation

Using the @nalipar's example on my OS X.

$ wc -c /etc/group
    2317 /etc/group

$ gwc -c /etc/group #the GNU version of the wc
2317 /etc/group

the system default wc

(dd ibs=500 skip=1 count=0; wc -c) < /etc/group

prints

0+0 records in
0+0 records out
0 bytes transferred in 0.000012 secs (0 bytes/sec)
    2317

using the GNU wc

(dd ibs=500 skip=1 count=0; gwc -c) < /etc/group
0+0 records in
0+0 records out
0 bytes transferred in 0.000013 secs (0 bytes/sec)
1817

Upvotes: 0

anon
anon

Reputation:

The dd command is used with /etc/group as input. With those arguments, we have a block file of 99k, 1 block of 99k is skipped due to the ibs argumentand then 0 blocks of 99k are copied. Then you are using your custom command ./wc -c with the result of this command as input. What dd achieves in the end is to to ignore a block of 99k and then feed the remaining data into your custom command.

e.g.

$ wc -c /etc/group
1011 /etc/group
$ (dd ibs=500 skip=1 count=0; wc -c) < /etc/group
511

Of course you'll expect different results through your custom wc command.

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 80921

This command (dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group spawns a sub-shell (for the (list)) and attached /etc/group to that sub-shells standard input.

Inside that sub-shell the dd command is run (and inherits the sub-shell's standard input) with an input block size of 99k a skip count of 1 and blocks to copy count of 0. That will cause dd to seek 99k into its standard input stream and stop. When that is finished wc is then run (and inherits the sub-shell's standard input) and reports the number of characters left in the stream to be read (which, for all but enormous groups files will be nothing).

Is your wc implementation seeking back to the start of the file handle?

Upvotes: 4

Related Questions