如何存储目录中的文件列表到一个数组? [英] How to store directory files listing into an array?

查看:139
本文介绍了如何存储目录中的文件列表到一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上市到一个数组中的文件,然后遍历数组再存放。
下面是我所得到的,当我从控制台运行 LS -ls 命令。

I'm trying to store the files listing into an array and then loop through the array again. Below is what I get when I run ls -ls command from the console.

total 40
36 -rwxrwxr-x 1 amit amit 36720 2012-03-31 12:19 1.txt
4 -rwxrwxr-x 1 amit amit  1318 2012-03-31 14:49 2.txt

我写上面的数据存储到一个bash数组以下bash脚本。

The following bash script I've written to store the above data into a bash array.

i=0
ls -ls | while read line
do
    array[ $i ]="$line"        
    (( i++ ))
done

但是,当我回声$阵列,我什么也没得到!

仅供参考,我运行脚本是这样的: ./ bashscript.sh

FYI, I run the script this way: ./bashscript.sh

推荐答案

试着用:

#! /bin/bash

i=0
while read line
do
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -ls)

echo ${array[1]}

在你的版本中,,而运行在一个子shell,您在循环修改环境变量不是外面可见。

In your version, the while runs in a subshell, the environment variables you modify in the loop are not visible outside it.

(请记住,解析 LS的输出一般不是一个好想法在所有。)

(Do keep in mind that parsing the output of ls is generally not a good idea at all.)

这篇关于如何存储目录中的文件列表到一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆