Why does `xargs` not work with `echo` but work with `ls`

bashecholinuxlsxargs

root@home:~$ ls
root@home:~$ echo abc > z1
root@home:~$ echo xyz > z2
root@home:~$ ls
z1  z2
root@home:~$ ls | xargs -I{} cat {}
abc
xyz
root@home:~$ echo z1 z2 | xargs -I{} cat {}
cat: 'z1 z2': No such file or directory
root@home:~$ echo "z1 z2" | xargs -I{} cat {}
cat: 'z1 z2': No such file or directory

Why does xargs not work with echo but work with ls?

Best Answer

echo "z1 z2" is producing a single-line string:

z1 z2

ls is producing two lines:

z1
z2

You can replicate its behavior with echo -e, which will print \n as newlines:

$ echo -e "z1\nz2" | xargs -I{} cat {}
abc
xyz

Related Question