bash 脚本,创建目录中所有文件的数组 [英] bash script, create array of all files in a directory
本文介绍了bash 脚本,创建目录中所有文件的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含许多 .html 文件的目录 myDir
.我正在尝试创建目录中所有文件的数组,以便我可以索引该数组并能够引用目录中的特定 html 文件.我尝试了以下行:
I have a directory myDir
of many .html files. I am trying to create an array of all the files in the directory so I might be able to index the array and be able to refer to particular html files in the directory. I have tried the following line:
myFileNames=$(ls ~/myDir)
for file in $myFileNames;
#do something
但我希望能够拥有一个计数器变量并具有如下逻辑:
but I want to be able to have a counter variable and have logic like the following:
while $counter>=0;
#do something to myFileNames[counter]
我对 shell 脚本很陌生,无法弄清楚如何实现这一点,因此希望得到有关此问题的任何帮助.
I am quite new to shell scripting and am unable to figure out how to achieve this hence would appreciate any help regarding this matter.
推荐答案
您可以:
# use nullglob in case there are no matching files
shopt -s nullglob
# create an array with all the filer/dir inside ~/myDir
arr=(~/myDir/*)
# iterate through array using a counter
for ((i=0; i<${#arr[@]}; i++)); do
#do something to each element of array
echo "${arr[$i]}"
done
您也可以为数组的迭代执行此操作:
You can also do this for iteration of array:
for f in "${arr[@]}"; do
echo "$f"
done
这篇关于bash 脚本,创建目录中所有文件的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文