1

I am trying to do a script in bash and the idea is that I have an array with text and I use to creat a folder, for example:

#!/bin/bash
dir=(dir1 dir2 dir3)
for i in 0 1 2; do
    d=run_${#dir[i]}
    echo "Prepare case ${d}..."
done

My problem is that when I do this, it prints:

Prepare case run_4...
Prepare case run_4...
Prepare case run_4...

and the number 4 corresponds to the lenght of each array element, (if I change dir1 to direc1 for example, I get in the first line of the output "Prepare case run_6...")

What i was looking:

Prepare case run_dir1...
Prepare case run_dir2...
Prepare case run_dir3...

What i am missing?

3
  • 2
    Then why did you use ${#? What do you think # means? Commented Sep 23, 2020 at 13:51
  • 1
    Bookmark this link. Commented Sep 23, 2020 at 13:54
  • why not just use your $i directly, or at least d=run_${i}. Good luck. Commented Sep 23, 2020 at 14:09

1 Answer 1

1

Remove # from this commnd d=run_${#dir[i]}

And you can loop over array values like this:

for i in "${dir[@]}"; do
    echo "Prepare case run_$i..."
done
Sign up to request clarification or add additional context in comments.

Comments

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.