Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help using xargs to pass mulitiple filenames to shell script

Tags:

shell

unix

Can someone show me to use xargs properly? Or if not xargs, what unix command should I use?

I basically want to input more than (1) file name for input <localfile>, third input parameter.

For example:

1. use `find` to get list of files
2. use each filename as input to shell script

Usage of shell script:

test.sh <localdir> <localfile> <projectname>

My attempt, but not working:

find /share1/test -name '*.dat' | xargs ./test.sh /staging/data/project/ '{}' projectZ \;

Edit: After some input from everybody and trying -exec, I am finding that my <localfile> filename input with find is also giving me the full path. /path/filename.dat instead of filename.dat. Is there a way to get the basename from find? I think this will have to be a separate question.

like image 584
jdamae Avatar asked Dec 28 '22 15:12

jdamae


2 Answers

I'd just use find -exec here:

% find /share1/test -name '*.dat' -exec ./test.sh /staging/data/project/ {} projectZ \;

This will invoke ./test.sh with your three arguments once for each .dat file under /share1/test.

xargs would pack up all of these filenames and pass them into one invocation of ./test.sh, which doesn't look like your desired behaviour.

like image 173
Johnsyweb Avatar answered Feb 08 '23 23:02

Johnsyweb


If you want to execute the shell script for each file (as opposed to execute in only once on the whole list of files), you may want to use find -exec:

find /share1/test -name '*.dat' -exec ./test.sh /staging/data/project/ '{}' projectZ \;

Remember:

  • find -exec is for when you want to run a command on one file, for each file.
  • xargs instead runs a command only once, using all the files as arguments.
like image 28
Danilo Piazzalunga Avatar answered Feb 08 '23 23:02

Danilo Piazzalunga