LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   script to execute a command multiple times (http://www.linuxquestions.org/questions/programming-9/script-to-execute-a-command-multiple-times-683748/)

snr8fl3 11-16-2008 05:56 AM

script to execute a command multiple times
 
I wish to have a command that executes a specified command a specified number of times.

For example,
Code:

multi 3 echo abc
should execute 'echo abc' three times.

Closest I can get is this bash function:
Code:

function multiq { i=$1; while [ $i -gt 0 ]; do $2; i=$(( $i - 1 )); done; }
,which is used like :
Code:

multiq 3 'echo abc'
.

I also want to have a command that opens a specified x application a specified number of times. For example,
Code:

multix 3 xterm python
should open three xterm windows with python as shell, that is same as executing 'xterm python &' three times.

I tried this bash function:
Code:

function multix { i=$1; while [ $i -gt 0 ]; do $2 & ; i=$(( $i - 1 )); done; }
, but this results in bash syntax error.

How should I implement multi and multix? Are there programs that does similar thing?

acid_kewpie 11-16-2008 06:14 AM

this looks a *lot* like homework as these functions seem completely arbitrary and straightforward, but if they are you've re-written it pretty well... :) Either way, please don't ask homework questions

a couple of pointers though. while loops are ok, but not really what you want. Try a for loop instead, and also read up on the "shift" command.

snr8fl3 11-16-2008 01:00 PM

Code:

function multi { n=$1; shift; for ((i=0;i<n;i++)) do $@; done; }
function background { $@ &}
function multibg { n=$1; shift; for ((i=0;i<n;i++)) do background $@; done; }

This is not really arbitrary (not homework). One can open several remote shells quickly using such commands.

Code:

ssh -X username@hostname multibg 4 xterm -someoption

acid_kewpie 11-16-2008 01:12 PM

Code:

function background { $@ &}
Why use one character for put something into the background when 10 will do?! Very useful. :)

snr8fl3 11-17-2008 12:11 AM

Code:

$ function multibg { n=$1; shift; for ((i=0;i<n;i++)) do $@ &; done; }
The obvious approach like this doesn't work. Not familiar with bash programming.

The_Kernel 11-17-2008 12:49 PM

So long as your args are in a fixed place this would work:

Code:

for i in $(seq 1 $1)
do
  $( sed "s:^$1 ::" <<< $@ ) &
done

Just remove the trailing '&' for the "multiq" version


All times are GMT -5. The time now is 05:44 AM.