首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UNIX AIX使用Array存储名称和路径,然后单独使用for循环

UNIX AIX使用Array存储名称和路径,然后单独使用for循环
EN

Unix & Linux用户
提问于 2019-10-08 19:30:14
回答 1查看 630关注 0票数 -1

我有一个脚本,在其中我需要创建一个数组,其中包含一些文件的路径和名称,

然后,在检查用户的arg之后,我需要将路径和名称分别传递给另一个脚本,以匹配数组中的一个名称

代码语言:javascript
复制
array1[0]="/Distenation1/File1.txt"
array1[1]="file1"

#testing another way to set an array
set -A array2 "/Distenation2/File2.txt" file2

这里出现了一个问题,因为我无法找到将数组作为整体传递的方法,然后在for循环中将用户arg $1file2 1file2 2等匹配,并将相应的路径传递给另一个脚本:

代码语言:javascript
复制
#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来显示一个示例:

代码:

代码语言:javascript
复制
for i in ${array1[@]} ${array2[@]}
do
    echo Name : ${i[1]} '\n'Path : ${i[0]}
done

产出:

代码语言:javascript
复制
Name :
Path : /Distenation1/file1.txt
Name :
Path : file1
Name :
Path : /Distenation2/file2.txt
Name :
Path : file2

所需的结果应是:

代码语言:javascript
复制
Name : file1
Path : /Distenation1/file1.txt
Name : file2
Path : /Distenation2/file2.txt
EN

回答 1

Unix & Linux用户

发布于 2019-10-10 17:28:46

我尝试了一项我认为我能理解的工作:

代码语言:javascript
复制
#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;

产出:

代码语言:javascript
复制
=>test1 file1
Name : file1
 Path : /Distenation1/File1.txt

我不确定这是否是最佳实践,但我对任何更好的解决方案或优化代码都持开放态度,因为我正在处理一个非常大的脚本,每一毫秒的优化都会产生不同的效果。

票数 0
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/545781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档