Double variable in bash

Jose ruanova casas :
#! /bin/bash

source_id="1 2 3 4 5 "
target_id="one two three four five"


for $target_id in ${!source_id[*]}
do
    echo " id " $target_id is " name is "${source_id[$targetid]}
done

I want print:

name is 1 id is one  
name is 2 id is two

and so on…

Mihir :

bash v4+, solution with associative arrays:

If you have bash version greater than 4, this way might be better:

target_id=(
    ["1"]="one"
    ["2"]="two"
    ["3"]="three"
    ["4"]="four"
    ["5"]="five"
)

for source_id in ${!target_id[*]}
do
    echo "name is ${target_id["${source_id}"]} id is "${source_id}""
done

Here read more about associative arrays in bash: Associative arrays in bash

Solution with regular arrays:

source_id=(1 2 3 4 5)
target_id=("one" "two" "three" "four" "five")

array_len="${#source_id[@]}"

for (( index = 0 ; index < "${array_len}" ; index++ ))
do
    echo "name is ${target_id[${index}]} id is ${source_id[${index}]}"
done

You can read about bash arrays here : bash arrays

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346003&siteId=1