Tizi Toure
Tizi Toure

Reputation: 41

How can I search and execute two scripts simultaneously in Unix?

Suppose you have a folder that contains two files.

Example: stop_tomcat_center.sh and start_tomcat_center.sh.

In my example, the return of ls *tomcat* returns these two scripts. How can I search and execute these two scripts simultaneously?

I tried

ls *tomcat* | xargs sh

but only the first script is executed (not the second).

Upvotes: 2

Views: 135

Answers (3)

Samuel Kirschner
Samuel Kirschner

Reputation: 1185

xargs is missing the -n 1 option.

From man xargs:

-n max-args, --max-args=max-args

Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit.

xargs otherwise tries to execute the command with as many parameters as possible, which makes sense for most commands.

In your case ls *tomcat* | xargs sh is running sh stop_tomcat_center.sh start_tomcat_center.sh and the stop_tomcat_center.sh is probably just ignoring the $1 parameter.


Also it is not a good idea to use the output of ls. A better way would be to use find -maxdepth 1 -name '*tomcat*' -print0 | xargs -0 -n 1 sh or for command in *tomcat*; do sh "$command"; done


This answer is based on the assumption that the OP meant "both with one command line" when he wrote "simultaneously".

For solutions on parallel execution have take a look at the other answers.

Upvotes: 1

unixmiah
unixmiah

Reputation: 3145

You can do the following to search and execute

find . -name "*.sh" -exec sh x {} \;

find will find the file and exec will find the match and execute

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207465

An easy way to do multiple things in parallel is with GNU Parallel:

parallel ::: ./*tomcat*

Or, if your scripts don't have a shebang at the first line:

parallel bash ::: ./*tomcat*

Or if you like xargs:

ls *tomcat* | xargs -P 2

Upvotes: 2

Related Questions