Shell Script – Purpose of xargs -I Command

shell-scriptxargs

Can you explain what this command does:

files=(this_is_filename)
for filename in ${files[@]}; do 
  ls -t1 ../htory/$filename* |
    head -1 |
    xargs -I fname cp -p fname ../htory2/somefile.CSV
done

Especially this part of this command

xargs -I fname cp -p fname ../htory2/somefile.CSV

Best Answer

xargs transforms input to arguments. The -I option specifies the string to be used as a placeholder for the argument. Therefore, if the pipeline outputs something like

file1
file2

then the xargs line transforms that to

cp -p file1 ../htory2/somefile.CSV
cp -p file2 ../htory2/somefile.CSV

The head -1 only returns one line, though, so I can see no real benefit of using xargs instead of, say

cp -p "$(ls -t1 ../htory/$filename* | head -1)" ../htory2/somefile.CSV

Moreover, since the target file is always the same, it will be overwriten by the last file in ${files[@]}.

Related Question