我正在尝试将文件列表存储到一个数组中,然后再次遍历该数组.下面是我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
Run Code Online (Sandbox Code Playgroud)
我写的以下bash脚本将上述数据存储到bash数组中.
i=0
ls -ls | while read line
do
array[ $i ]="$line"
(( i++ ))
done
Run Code Online (Sandbox Code Playgroud)
但是当我echo $array
,我什么都没得到!
仅供参考,我这样运行脚本: ./bashscript.sh
gle*_*man 88
我用了
files=(*)
Run Code Online (Sandbox Code Playgroud)
然后,如果您需要有关文件的数据(例如大小),请stat
在每个文件上使用该命令.
Mat*_*Mat 32
试试:
#! /bin/bash
i=0
while read line
do
array[ $i ]="$line"
(( i++ ))
done < <(ls -ls)
echo ${array[1]}
Run Code Online (Sandbox Code Playgroud)
在您的版本中,while
子shell中的运行,您在循环中修改的环境变量在其外部不可见.
(请记住,解析输出ls
通常不是一个好主意.)
这可能对你有用:
OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"
Run Code Online (Sandbox Code Playgroud)
这是一个变体,可让您使用正则表达式模式进行初始过滤,更改正则表达式以获取所需的过滤。
files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
printf " %s\n" $item
done
Run Code Online (Sandbox Code Playgroud)