Accessing an array item by index in bash
I have the following code:
PROJECT_TYPES="iPad iPho开发者_运维问答ne"
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
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
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
精彩评论