csh/sh for loop - how to?

Paul J picture Paul J · May 13, 2011 · Viewed 54.4k times · Source

i'm trying to write a for loop that executes 2 scripts on FreeBSD. I don't care if it's written in sh or csh. I want something like:

for($i=11; $i<=24; $i++)
{
   exec(tar xzf 'myfile-1.0.' . $i);
   // detect an error was returned by the script
   if ('./patch.sh')
   {
      echo "Patching to $i failed\n";
   }
}

Does anyone know how to do this please?

Thanks

Answer

William Pursell picture William Pursell · May 13, 2011

The typical way to do this in sh is:

for i in $(seq 11 24); do 
   tar xzf "myfile-1.0$i" || exit 1
done

Note that seq is not standard. Depending on the availability of tools, you might try:

jot 14 11 24

or

perl -E 'say for(11..24)'

or

yes '' | nl -ba | sed -n -e 11,24p -e 24q

I've made a few changes: I abort if the tar fails and do not emit an error message, since tar should emit the error message instead of the script.