我有一个脚本,需要在其中创建一个包含某些文件的路径和名称的数组,
然后我需要在检查用户的参数与数组中的名称之一匹配后将路径和名称分别传递给另一个脚本
array1[0]="/Distenation1/File1.txt"
array1[1]="file1"
#testing another way to set an array
set -A array2 "/Distenation2/File2.txt" file2
问题来了,因为我找不到一种方法来传递整个数组,然后在 for 循环中我想匹配用户参数 $1和文件1或者文件2依此类推,并将相应的路径传递给另一个脚本:
#the following code doesnt work as needed -logically-
for i in ${array1[@]} ${array2[@]}
do
if [ $1 = ${i[1]} ]
then
./sendfile ${i[0]}
fi;
done
编辑:我看来的ksh版本=版本M-11/16/88f
使用与上面相同的代码,但使用 echo 来显示示例:
代码:
for i in ${array1[@]} ${array2[@]}
do
echo Name : ${i[1]} '\n'Path : ${i[0]}
done
输出 :
Name :
Path : /Distenation1/file1.txt
Name :
Path : file1
Name :
Path : /Distenation2/file2.txt
Name :
Path : file2
所需的结果应该是:
Name : file1
Path : /Distenation1/file1.txt
Name : file2
Path : /Distenation2/file2.txt
答案1
我尝试了一种我认为我理解的解决方法:
#put all the data inside 1 array
array1[0]="/Distenation1/File1.txt"
array1[1]="file1"
array1[2]="/Distenation2/File2.txt"
array1[3]="file2"
#create a counter
n=0
#the trick here was that 'i' (loop) stores 1 array data per iteration (at first i thought it stores the whole array data then go through them 1 by one)
for i in ${array1[@]}
do
if [ $1 = ${i} ]
then
#here i had to call the original array to be able to read through any data inside the array
echo Name : $i '\n' Path : ${array1[$n+1]}
fi;
let n=n+1
done;
输出 :
=>test1 file1
Name : file1
Path : /Distenation1/File1.txt
我不确定这是否是最佳实践,但我愿意接受任何更好的解决方案或优化的代码,因为我正在使用一个非常大的脚本,每一毫秒的优化都会产生影响