0

I have a use case where few variables are defined as

test1="12 33 44 55"
test2="45 55 43 22"
test3="66 54 33 45"

i=1;
while [ $i -le 3 ]; do

      #parse value of test1 test2 test3
      startProcess $test$i
      i=$((i+1))
      done

startProcess () {

    #Should print the complete string which is "12 33 44 55" everytime
     echo $1 
}

I need to pass the test1, test2, test3 variable values in loop and echo them completely in the function.

Please suggest

2

Use an array:

#!/bin/bash

startProcess () {
    printf 'Argument: %s\n' "$1"
}

testarr=( "12 33 44 55" "45 55 43 22" "66 54 33 45" )

for test in "${testarr[@]}"; do
    startProcess "$test"
done

Output:

Argument: 12 33 44 55
Argument: 45 55 43 22
Argument: 66 54 33 45

Or, use an associative array (in bash 4.0+):

#!/bin/bash

startProcess () {
    printf 'Argument: %s\n' "$1"
}

declare -A testarr
testarr=( [test1]="12 33 44 55"
          [test2]="45 55 43 22"
          [test3]="66 54 33 45" )

for test in "${!testarr[@]}"; do
    printf 'Running test %s\n' "$test"
    startProcess "${testarr[$test]}"
done

Output:

Running test test1
Argument: 12 33 44 55
Running test test2
Argument: 45 55 43 22
Running test test3
Argument: 66 54 33 45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.