Shell脚本将值从命令行传递到Array

时间:2014-02-25 06:40:49

标签: arrays bash shell command

在将命令行中的值分配给数组时,我遇到了一个关于bash shell脚本的小问题。例如,如果我输入$./test.sh aa bb cc,我希望将值分配给数组E.g

test[0]=aa
test[1]=bb
test[2]=cc

它应该是无限的,它必须根据用户输入创建数组。

这是我的代码

谢谢

#!/usr/bin/bash
count2=1
declare -a mvne $count2
while [ $# -gt $count2 ]
do
mvne[$count2]=$"[$count2]"  <---here is the problem, how do i assign the command line parameter to the array

echo ${mvne[$count2]}
count2=`expr $count2 + 1`
done   

1 个答案:

答案 0 :(得分:0)

位置参数已经是数组式的。您可以将它们分配给另一个数组而不进行循环:

#!/bin/bash
count2=0
declare -a mvne
mvne=( "$@" )
while [ $# -gt $count2 ]
do
    echo $count2: ${mvne[$count2]}
    ((count2++))
done

在命令行上运行时:

$ bash test.sh aa bb cc
0: aa
1: bb
2: cc
相关问题