Skip to content
Tags

,

Remove a shell loop: xargs unusual usage

28/09/2014

I would like to write down an unknown, yet very useful, usage of xargs(1).

In short, if I want to run a command on a list of files stored in a file, I could simply go for:

$ xargs -n1 ls -lh < files.lst

There is no magic here, after all this is the normal operation of xargs. But, we are mostly used in using xargs together with find(1), where again it applies a shell command on a file list, reading again from its standard input.

$ find -name '*.h' | xargs wc -l

What I have never realized is the fact that its standard input can come from a file. This is so commonly used pattern that I used to write it as:

$ for f in $(cat files.lst); do ls -lh $f; done

Although the loop construct looks clearer and the intention is reflected by shell’s syntax, it is though inefficient and needs far more keystrokes to be written.

I found this unusual usage of xargs at Design by Typing.

Advertisements

From → Linux, Shell

Leave a Comment

What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: