Praise the Lord and pass the arguments!

How to use xargs

One interesting utility in Unix is the little xargs command. It takes something from standard input and passes it as an argument to another command. For example, if a command expects a user name, you can get that name from somewhere and feed it to the command through xargs:

whoami | xargs passwd

The silly example above is also superfluous—passwd can accept a user name through standard input directly, so xargs isn’t needed here. And of course, passwd with no arguments would change the current user’s password anyway. But this is a simple way to illustrate what xargs does. Some commands don’t look for a required argument in the standard input stream, so they won’t read directly from the pipe. xargs takes whatever is in the pipe and sends it as an argument to the command that follows; in this case, passwd.

I personally use xargs in my .xinitrc file to set a random background wallpaper on my desktop when I start X:

find ~/pictures/wallpapers -type f | sort -R | tail -1 | xargs feh --bg-fill

The find command locates all the files in my wallpapers directory. The sort command puts the file names in random order and the tail command grabs only the last one in the list. xargs then passes that to feh, an image display utility, which sets the randomly selected file as my wallpaper. And so X greets me with a surprise every time I go GUI.

Be seeing you.

One thought on “Praise the Lord and pass the arguments!

Leave a Reply

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

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

Facebook photo

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

Connecting to %s