tags:

views:

63

answers:

4

How can one loop a command/program in a Unix shell without writing the loop into a script or other application.

For example, I wrote a script that outputs a light sensor value but I'm still testing it right now so I want it run it in a loop by running the executable repeatedly.

Maybe I'd also like to just run "ls" or "df" in a loop. I know I can do this easily in a few lines of bash code, but being able to type a command in the terminal for any given set of command would be just as useful to me.

+4  A: 

You can write the exact same loop you would write in a shell script by writing it in one line putting semicolons instead of returns, like in

for NAME [in LIST ]; do COMMANDS; done

At that point you could write a shell script called, for example, repeat that, given a command, runs it N times, by simpling changing COMMANDS with $1 .

klez
Thanks, I opted for infinite with while: while [ 1 ]; do sudo ./sensorTest.py; done
cdated
+1  A: 

Aside from accepting arguments, anything you can do in a script can be done on the command line. Earlier I typed this directly in to bash to watch a directory fill up as I transferred files:

while sleep 5s
do
  ls photos
end
Benson
+2  A: 

This doesn't exactly answer your question, but I felt it was relavent. One of the great things with shell looping is that some commands return lists of items. Of course that is obvious, but a something you can do using the for loop is execute a command on that list of items.

for $file in `find . -name *.wma`; do cp $file  ./new/location/ done;

You can get creative and do some very powerful stuff.

Eric U.
That is a powerful technique, but it fails if filenames have spaces in them. Also, `{}` is meaningless in your example. You need a variable: `for item in $list; do echo "$item"; done`
Dennis Williamson
find is a bad example, since its `-exec` argument does the same thing as the for loop, but in a space-friendly way. Still, it's a great technique and I use it frequently.
Benson
+2  A: 

I recommend the use of "watch", it just do exactly what you want, and it cleans the terminal before each execution of the commands, so it's easy to monitor changes.

You probably have it already, just try watch ls or watch ./my_script.sh. You can even control how much time to wait between each execution, in seconds, with the -n option, and you can use -d to highlight the difference in the output of consecutive runs.

Try:

Run ls each second:

watch -n 1 ls

Run my_script.sh each 3 seconds, and highlight differences:

watch -n 3 -d ./my_script.sh

watch program man page: http://linux.die.net/man/1/watch

Spidey