Search code examples
bashprintingxargsls

Why ls -1 | xargs -I{} echo -n {}{}{} does not print in right order?


Ubuntu$ ls -1

file1 file2

Ubuntu$ ls -1 | xargs -I{} echo -n {}{}{}

file1file1file1file2file2file2

Why don't I get the result in this order?: file1file2file1file2file1fil2


Solution

  • Because xargs executes the command (echo) for each word in its input. And of course {} is the same each time. Even if you repeat it many times.

    You can do what you want using for:

    ls=$(ls -1)
    for i in {1..3}
    do
      echo $ls
    done
    

    Example of usage:

    $ mkdir d ; cd d
    <d>$ touch file1 file2 file3
    <d>$ ls=$(ls -1)
    <d>$ for i in {1..3}
    > do
    >   echo $ls
    > done
    file1 file2 file3
    file1 file2 file3
    file1 file2 file3