Click to See Complete Forum and Search --> : stupid question on for loop
soleblazer
06-06-2007, 03:15 PM
Gents/Ladies,
I have what is probably a stupid question, but I cant figure it out.
In bash, is it possible to do arithmetic next to alphas in a for loop? Here is what I'm trying to do:
for tape in LNX001-LNX200
do
vmchange -h <hostname> -new_mt hcart3 -m $tape
done
Now, LNX001-LNX200 is LNX001 to LNX200, is there an easy way to do this, have it loop through LNX001, LNX002, and so forth?
How about this:
for tape in `seq -f LNX%03g 1 200`
do
echo $tape
vmchange -h <hostname> -new_mt hcart3 -m $tape
done
asarch
06-06-2007, 05:04 PM
Or even better:
This is for the TCSH shell but it will give you an idea:
#!/bin/tcsh -f
set I = 1
while ($I <= 2000)
if ($I < 10) then
set DEVICE = "LNX00$I"
endif
if ($I > 10 && $I < 100) then
set DEVICE = "LNX0$I"
endif
if ($I > 100) then
set DEVICE = "LNX$I"
endif
echo $DEVICE
@ I ++
end
Copy and paste on a file called count.csh and run it from any shell:
[$] ./count.csh
...
soleblazer
06-06-2007, 05:04 PM
dang, forgot about seq, that works nicely!
Thanks alot!
Or even better:
...
There is an error in the if statements though. It doesn't handle numbers like 10 and 100, because none of the if statements cater for it, so LNX010 and LNX100 is missed.
Besides:
xrx@therm-sempron:~/temp/forumJL$ time ./count.csh > /dev/null
real 0m0.682s
user 0m0.464s
sys 0m0.192s
xrx@therm-sempron:~/temp/forumJL$ time ./seq-count-2000.sh > /dev/null
real 0m0.100s
user 0m0.064s
sys 0m0.016s
;)
However, your code is more customizable though, if there happened to be more exotic requirements, your style would work better.