Thursday, November 19, 2015

linux - How to run a command multiple times, using bash shell?




Is there a way to run a command (e.g. ps aux|grep someprocess) for n times?



Something like:



run -n 10  'ps aux|grep someprocess'


I want to use it interactively, please do not post scripts.



Update: The reason I am asking this is, that I do work on a lot of machines and I don't want to import all my adaped scripts etc into every box to get the same functionality accross every machine.



Answer



I don't think a command or shell builtin for this exists, as it's a trivial subset of what the Bourne shell for loop is designed for and implementing a command like this yourself is therefore quite simple.



For starters you can use a dummy for loop:



for i in `seq 10`; do command; done


Or equivalently as per JimB's suggestion, using the Bash builtin for generating sequences:




for i in {1..10}; do command; done


This iterates ten times executing command each time - it can be a pipe or a series of commands separated by ; or &&. You can use the $i variable to know which iteration you're in.



If you consider this one-liner a script and so for some unspecified (but perhaps valid) reason undesireable you can implement it as a command, perhaps something like this on your .bashrc (untested):



#function run
run() {
number=$1

shift
for i in `seq $number`; do
$@
done
}


Usage:



run 10 command



Example:



run 5 echo 'Hello World!'

No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...