1

I have the following code:

#!/bin/bash

SECTION[1]="900px"
PATH[1]="/path/to/folder"

SECTION[2]="1080px"
PATH[2]="/patj/to/folder2"

SECTION[3]="3000px"
PATH[3]="/patj/to/folder3"

for i in {1..3}
do
    echo "${SECTION[$i]}"
    echo "${PATH[$i]}"
done

How can I make the for loop iterate through the number of sections?

I tried:

for i in {1.."${#SECTION[@]}"}

But I get an operand expected error.

2
  • Works for me with bash 4.3.48 if I only use builtin commands.. This might help: linfo.org/path_env_var.html Commented Aug 15, 2019 at 10:36
  • I should have mentioned that I'm on macos, I think the bash default bash version is 3.2. Commented Aug 15, 2019 at 10:47

1 Answer 1

1

You can use the C like for loop syntax

for ((i=1;i <= ${#SECTION[@]};i++))
do 
    echo "${SECTION[$i]}"
    echo "${PATH[$i]}" 
done

Or with seq

for i in $(seq ${#SECTION[@]})
do 
    echo "${SECTION[$i]}"
    echo "${PATH[$i]}" 
done
Sign up to request clarification or add additional context in comments.

2 Comments

That seq example looks so much more elegant - thanks so much. Love this place :-)
seq one around ~20-30% faster based on my tests but it required the seq command to be available.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.