1

I am trying to write a bash script which allows me to automate the creation of multiple directories with incrementing names.

For example, I am trying to create the directories named v0v1, v1v2, ... , v40v41.

I have tried using a 'for' loop, where I create a variable and set this to be equal to the current value of i+1 (where 'i' is the current loop iteration), but it is not working as expected. I have managed to get the variable to increment (and have checked this using 'echo'), but I cannot get it to become part of the new directory name.

The code I have written is as follows:

for i in {0..40}; do let r=$((i+1)); mkdir v$iv$r; done

However, the directories produced have names only containing the first variable value (i.e. v0, v1, ..., v40), and do not include the 'v$r' at all.

Does anyone have any ideas how to use two variables at once in the same filename?

2 Answers 2

1
printf 'r=%d ; mkdir v$((r-1))v${r} ;' $(seq 2 41) |sh

You don't need a shell loop at all.

Sign up to request clarification or add additional context in comments.

Comments

0
for i in {0..40}; do let r=$((i+1)); mkdir v${i}v$r; done

When bash sees the expression v$iv$r, it substitutes in for variables iv and r. But, of course, there is no iv. So bash substitutes in the empty string. The solution is to use braces to assure that bash knows where the variable name ends. Thus: v${i}v$r.

1 Comment

For something this simple I'd skip the separate r and just for i in {0..40}; do mkdir v${i}v$((i+1)); done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.