【问题标题】:I am trying to store the outputs of ls in an array [duplicate]我正在尝试将 ls 的输出存储在一个数组中[重复]
【发布时间】:2019-07-12 09:58:26
【问题描述】:

当使用 Linux 命令“ls”时,我列出了一个目录中的所有文件。我试图将命令 ls 的结果存储在 bash 的数组中,然后我希望能够打印出数组的每个元素。

这是我尝试过的。

> file_array=( $<ls>) )

> file_array= 'ls'

我的第一个错误,而我的数组只打印出第二个“ls”。

【问题讨论】:

    标签: arrays bash


    【解决方案1】:

    解析ls的输出是not a good idea。如果你必须这样做,正确的语法应该是:

    files=($(ls))
    

    您可以改用 glob:

    files=(*)          # store file names in an array
    declare -p files   # show the contents of array
    
    for file in "${files[@]}"; do
      # do something with file
    done
    

    在第二个语句中,= 后面有一个空格,即 not the right syntax 用于分配。

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2019-04-03
      • 2020-04-13
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      相关资源
      最近更新 更多