Tag Archives: xargs

xargs Reminder

I remember using xargs at a previous workplace for pasting a multi-line text list (say, from a text file on my desktop) to generate a space-delimited line of text containing the items in the pasted list. For the life of me this morning I couldn’t remember how to do it, and most examples don’t use xargs in this way. Here’s my reminder that I hope might help others.

Say I had this list of students in a text file that looked like:

mary
bob
susan
jim
jennifer
xavier

and I needed to generate a quick Bash one-liner to process something for them on the command line.  If I wanted to use a for loop on the command line, I’d supply the for loop with a list of things separated by a space.  For example:

for x in bob sue larry
> do
> echo "Hi $x"
> done

and the output will be:

Hi bob
Hi sue
Hi larry

On to xargs: say those names are in a text file on my desktop, with one name per line:

mary
bob
susan
jim
jennifer
xavier

If I copy the text from the file and paste it into the Linux command window, each name will be on a separate line and be interpreted as a command:

$ mary
-bash: mary: command not found
$ bob
-bash: bob: command not found
$ susan
-bash: susan: command not found
$ jim
-bash: jim: command not found
$ jennifer
-bash: jennifer: command not found
$ xavier
-bash: xavier: command not found

Using xargs, I can paste the list into the window and get all the names on one line, each separated by a space.  I will type xargs <<EOF and press enter, then paste my text.  The ‘EOF’ part of the command specifies the end-of-file string, which is needed to tell xargs when I’m finished with the input.  After I paste the list, I enter EOF to finish the command:

$ xargs <<EOF
> mary
> bob
> susan
> jim
> jennifer
> xavier
> EOF

And the output:

mary bob susan jim jennifer xavier

I can then copy this single line and paste it in the for loop.  Sure, it’s not really efficient with three items, but it sure makes things easier when you’re working with 100 server names.