开发者

Accessing an array item by index in bash

开发者 https://www.devze.com 2023-04-03 01:50 出处:网络
I have the following code: PROJECT_TYPES=\"iPad iPho开发者_运维问答ne\" ANT_TARGET_NAMES=\"ipadf ipaf\"

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
0

精彩评论

暂无评论...
验证码 换一张
取 消