【问题标题】:Arrays not working in AIX KSH阵列在 AIX KSH 中不起作用
【发布时间】:2019-01-27 21:01:48
【问题描述】:

我有代码:

typeset -i idx=0
for each in `find . -name "*.log" -print `
do
        ILIST[idx]=`basename $each`
        idx=idx+1
        print :${ILIST[$idx]}:$each:$idx  << does not print array element "::file1.log:o"
done    # for each

print ${ILIST[@]}  << prints entire array as expected
exit

那么,如何打印数组的单个元素?它适用于 HPUX。目标是并排创建 2 个数组,其中一个是文件名,另一个是创建时间,以便可以检查该文件的时间。

【问题讨论】:

  • 您为数组元素idx 分配了一些东西,但随后您将其递增并打印元素idx+1,此时该元素始终为空。只需在循环的最后递增...
  • 我通常建议通过使用符合 POSIX 的数学语法 (idx=$((idx + 1 ))) 来避免对 typeset -i 的依赖——这样读者就不必过多关注上下文确保您的代码正常工作。
  • 不过,作为一个不同的问题 -- for each in $(find ...) 表面上是坏的;不处理带有空格、通配符等的文件或目录名称。请参阅UsingFind 了解更好的实践讨论——虽然它是一个以 bash 为中心的文档,但它确实讨论了显示的每个模式与不同 shell 和不同版本的兼容性find。同样,BashPitfalls #1 也适用于此。

标签: shell unix sh ksh aix


【解决方案1】:

首先,我无法访问 AIX 机器来测试语法是否良好,但它在 Linux 实现上运行良好。

由于 KSH 支持复合变量 (93l +),我认为您最好使用它们而不是 2 个数组。

这是一段可以做你想做的事情的代码(至少我认为:))

    #!/bin/ksh

    typeset -L50 Col1
    typeset -L25 Col2

    #need to give the path as a parameter here since it's a test script
    DIRNAME=$1

    idx=0
    #The caveat for "find" still apply, so I'm assuming there is no special characters nor space in the filenames
    for file in $(find $DIRNAME -type f -name "*.log")
    do
    #Full path name
            LOGFILE[$idx].FName=$file
    #Only File name
            LOGFILE[$idx].BName=$(basename $file)
    #Last modification time since the beginning of time in second as it is easier to manage afterward. There is no creation date per se on Linux at least
            LOGFILE[$idx].MDate=$(stat -c %Z $file)
            ((idx++))
    done

    Col1="Filename"
    Col2="Date"

    print "$Col1$Col2\n"

    #Some prefer the syntax ${#LOGFILE[@]} but won't make a difference here since it's an indexed array.
    for ((i=0;i<${#LOGFILE[*]};i++)); do
            Col1=${LOGFILE[$i].BName}
    #Translating the seconds to human date. Format can of course be modified at will
            Col2=$(date -d @"${LOGFILE[$i].MDate}" +"%Y%m%d%H%M")
            print "$Col1$Col2"
    done

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2018-04-16
    • 2011-12-10
    • 2014-08-01
    • 2018-08-23
    • 2017-04-19
    • 2013-06-12
    相关资源
    最近更新 更多