user1308144
user1308144

Reputation: 475

How to keep leading zeros in for-loop range

I have a directory containing many subdirectories (named 0001, 0002...), and I want to start a bash script running in each directory.

for i in {0001..0021}; do cd $i; ../script1.sh; cd ..; done

With the above it ignores the 000 and takes the range as 1 to 21. How do I get it to take the 0's into account?

Upvotes: 0

Views: 527

Answers (4)

michael501
michael501

Reputation: 1482

yet another way of doing this ( my way and fastest )

 for i in 000{1..21}; do cd ${i:(-4)}; ../script1.sh; cd ..; done

Upvotes: 0

jkshah
jkshah

Reputation: 11703

I want to start a bash script running in each directory.

Then you can simply use *

for i in *; do cd $i; ../script1.sh; cd ..; done

Upvotes: 2

anubhava
anubhava

Reputation: 785276

You can use ((...)) in BASH:

for ((i=0; i<=21; i++)); do j=$(printf "%04d" $i); cd $j; ../script1.sh; cd ..; done

Upvotes: 0

nneonneo
nneonneo

Reputation: 179452

for i in {1..21}; do
    i=`printf '%04d' $i`
    # do stuff with $i (now in the format 0001)
done

Upvotes: 3

Related Questions