5

I have a directory with folders sequentially numbered 1-1000, however I want to perform an action for some of the folders in this directory. i.e folders 1-50. How do I define the start and end point of the loop?

So far I have a script along these lines:

a=1
b=1

for i in ~/PATH/*/ ;do

(cd $i/ && action)

echo "completed"
a=`expr $a + $b`

echo "Next Folder"
done

I can define the start of the loop by changing a= but I am not sure how to define the end to the loop? As it stands, it will keep going through all the folders in that directory. Thanks :)

  • Look up c-style for loop. – 123 Jul 25 '16 at 14:26
4
#!/bin/bash
a=1
b=1

cd ~/PATH/
for i in $(ls -v) ;do
  (cd $i/ && action) && echo "completed" || echo "error"
  a=$((a+b)); [ "$a" -gt 50 ] && break 
  echo "Next Folder"
done
  • 1
    That does the first 50 in the shell's glob expansion, but if the names are without leading zeros like 1 2 3 ... 9 10 11 12 ... 99 100 101 102 ... 999 1000 (which is not clearly seated either way) then the first 50 are 1 10 100 1000 1001 1002 ... 1046 which is not the requested 1-50. – dave_thompson_085 Jul 26 '16 at 5:28
  • I do a little modification to fix this. – Luciano Andress Martini Jul 26 '16 at 15:01
7

Using the command seq to generate the list over which to iterate:

for nn in $(seq 1 50) ; do
    (cd someprefix/$nn && action)
done

Or, if your shell supports brace expansion:

for nn in {1..50} ; do
    (cd someprefix/$nn && action)
done
4

The break command allows you to break out of a loop.

So you would do something like this, after setting a

if [ $a -gt 50 ]
then
  break
fi
4

Bash allows for loops that looks like the standard C for-loop:

for (( i = 1; i <= 50; ++i )); do
  ( cd $i && action )
done

Change cd $i to cd "$HOME/PATH/$i" or whatever the path is to your directories.

2

You can even do a while loop instead:

a=1
while [ $a -le 50 ]; do
   (cd $a/ && action) 
   a=$((a+1))
done

Or, alternatively:

a=1
while (( ++a<=50 ));do
   (cd $a/ && action) 
done
  • OP said it starts on 1, so maybe a=1? Another while could also be while (( ++a<=50 ));do – 123 Jul 25 '16 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.