打印变量值将打印字符串Shell脚本

学习代码

我有一个用例,其中很少有变量被定义为

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 
}

我需要在循环中传递test1,test2,test3变量值,并在函数中完全回显它们。

请建议

库萨兰达

使用数组:

#!/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

输出:

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

或者,使用关联数组(bash4.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

输出:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章