csh/sh for loop - how to?
i'm trying to write a for开发者_JS百科 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
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.
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.
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 < 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
I think you should just use bash. I don't have it here, so it cannot test it, but something along this should work:
for ((I=11; I<=24; I++)) ; do
tar xzf myfile-1.0.$I || echo Patching to $I failed
done
EDIT: Just read the comments and found out there's no bash in FreeBSD default installation. So this might not work at all - I'm not sure about the differences between (t)csh and bash.
Well what i just did is the following.
sh
Load sh shell and then for loop works like on linux.
for i in 1 2 3 4 5 6 7 8 9; do dd if=/dev/zero of=/tmp/yourfilename$i.test bs=52428800 count=15; done
精彩评论