Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csh/sh for loop - how to?

Tags:

bash

shell

sh

csh

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

like image 588
Paul J Avatar asked May 13 '11 14:05

Paul J


3 Answers

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.

like image 124
William Pursell Avatar answered Sep 20 '22 02:09

William Pursell


Wow! No BASH. And probably no Kornshell:

i=11
while [ $i -le 24 ]
do
    tar xzf myfile-1.0.$i
    i=`expr $i + 1`
    if ./patch.sh
    then
        echo "patching to $i failed"
    fi
done

Written in pure Bourne shell just like God intended.

Note you have to use the expr command to add 1 to $i. Bourne shell doesn't do math. The backticks mean to execute the command and put the STDOUT from the command into $i.

Kornshell and BASH make this much easier since they can do math and do more complex for loops.

like image 40
David W. Avatar answered Sep 22 '22 02:09

David W.


csh does loops fine, the problem is that you are using exec, which replaces the current program (which is the shell) with a different one, in the same process. Since others have supplied sh versions, here is a csh one:

    #!/bin/csh
    set i = 11
    while ($i &lt 25)
        tar xzf "myfile-1.0.$i"

        # detect an error was returned by the script   
        if ({./patch.sh}) then     
            echo "Patching to $i failed"   
        endif
        @ i = $i + 1
    end

Not sure about the ./patch.sh are you testing for its existence or running it? I am running it here, and testing the result - true means it returned zero. Alternatively:

        # detect an error was returned by the script   
        if (!{tar xzf "myfile-1.0.$i"}) then     
            echo "Patching to $i failed"   
        endif
like image 38
cdarke Avatar answered Sep 22 '22 02:09

cdarke