bash 如何将目录文件列表存储到数组中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9954680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:53:38  来源:igfitidea点击:

How to store directory files listing into an array?

bashshell

提问by codef0rmer

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 -lscommand from the console.

我正在尝试将列出的文件存储到一个数组中,然后再次遍历该数组。以下是我ls -ls从控制台运行命令时得到的结果。

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

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

我编写的以下 bash 脚本将上述数据存储到 bash 数组中。

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

But when I echo $array, I get nothing!

但是当我echo $array,我什么也得不到!

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

仅供参考,我以这种方式运行脚本: ./bashscript.sh

采纳答案by Mat

Try with:

尝试:

#! /bin/bash

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

echo ${array[1]}

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

在您的版本中,while在子shell 中运行,您在循环中修改的环境变量在其外部不可见。

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

(请记住,解析 的输出ls通常根本不是一个好主意。)

回答by glenn Hymanman

I'd use

我会用

files=(*)

And then if you need data about the file, such as size, use the statcommand on each file.

然后,如果您需要有关文件的数据,例如大小,请stat对每个文件使用该命令。

回答by harschware

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

这是一个变体,它允许您使用正则表达式模式进行初始过滤,更改正则表达式以获得您想要的过滤。

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

回答by potong

This might work for you:

这可能对你有用:

OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"

回答by rashok

Running any shell command inside $(...)will help to store the output in a variable. So using that we can convert the files to array with IFS.

在里面运行任何 shell 命令$(...)将有助于将输出存储在一个变量中。因此,使用它我们可以将文件转换为数组IFS

IFS=' ' read -r -a array <<< $(ls /path/to/dir)