How to use xargs command in Linux with examples.

Here we will see what is xargs command and how can we use it to simplify the complex or long tasks on Linux.

What is xargs
Xargs stand for extended arguments.
It is used to provide extended arguments to a command from previous command/executable.

When xargs needed ?
It takes arguments automatically from standard input instead of waiting for manual intervention helps in making the scripts or automating tasks. Hence for any such requirement where the arguments to a command is to be provided automatically by standard input via output of another command, this command is useful.

xargs can handle bulk arguments. If you want to handle bulk arguments which can’t be handled by other commands directly like rm, cat, etc, then we you can use xargs.

How xargs reads arguments from previous command ?
To know how xargs reads from previous command, lets check out below example.

[root@nglinux ~]# ls | xargs file
anaconda-ks.cfg:    ASCII English text
Desktop:            directory
Documents:          directory
Downloads:          directory
edit_host.sh:       Bourne-Again shell script text executable
install.log.syslog: ASCII text
Music:              directory
Pictures:           directory
Public:             directory
Templates:          directory
test:               directory
Videos:             directory
[root@nglinux ~]#

In this example, we can see the output of ls command is sent to file command as an argument since xargs is used.

Now lets see another example of xargs to make it more clear.

XARGS example
Lets see an example where we will see what all files are there in directories present in CWD.

[root@nglinux ~]# ls -ltr | grep -i ^d | awk '{print $9}' | xargs ls
Desktop:
bluefish.desktop				   NGEL System Console.desktop
Install NGELinux on USB.desktop			   Terminal.desktop
Install NGELinux on your System Hard Disk.desktop

Documents:

Downloads:

Music:

Pictures:

Public:

Templates:

test:
file1  file2  file3  new.cpio  test2

Videos:
[root@nglinux ~]# 

Seems interesting and useful, so start using xargs command.

Do post your comments/questions/suggestions here.

Leave a Reply

Your email address will not be published.