Emidee
Emidee

Reputation: 1275

Accessing an array item by index in bash

I have the following code:

PROJECT_TYPES="iPad iPhone"
ANT_TARGET_NAMES="ipadf ipaf"

INDEX=0

for PROJECT_TYPE in $PROJECT_TYPES; do

echo "${PROJECT_TYPE} => ${ANT_TARGET_NAMES[$INDEX]}"

let "INDEX++"
done

This displays the following lines:

iPad => ipadf ipaf
iPhone =>

How can I change the code so it displays:

iPad => ipadf
iPhone =>  ipaf

???

Thanks in advance

Mike

Upvotes: 1

Views: 545

Answers (2)

glenn jackman
glenn jackman

Reputation: 246827

bash 4 has associative arrays so you could write:

declare -A targets=([iPad]=ipadf [iPhone]=ipaf)
for project_type in "${!targets[@]}"; do
  printf "%s => %s\n" "$project_type" "${targets[$project_type]}"
done

Otherwise, declare two arrays as in ennuikiller's answer, but I would iterate over the indices directly

projects=(iPad iPhone)
targets=(ipadf ipaf)
for (( i=0; i < ${#projects[@]}; i++ )); do
  printf "%s => %s\n" "${projects[$i]}" "${targets[$i]}"
done

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

The correct way to do this is:

INDEX=0
PROJECT_TYPES=(iPad iPhone)
ANT_TARGET_NAMES=(ipadf ipaf)

for PROJECT_TYPE in ${PROJECT_TYPES[*]} 
do 
echo "${PROJECT_TYPE} => ${ANT_TARGET_NAMES[$INDEX]}"  
let "INDEX++" 
done

Upvotes: 2

Related Questions