bash 脚本,创建目录中所有文件的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21668471/
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-10 00:39:35  来源:igfitidea点击:

bash script, create array of all files in a directory

arraysbashshellwhile-loop

提问by anonuser0428

I have a directory myDirof 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:

我有一个myDir包含许多 .html 文件的目录。我正在尝试创建目录中所有文件的数组,以便我可以索引该数组并能够引用目录中的特定 html 文件。我尝试了以下行:

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]

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.

我对 shell 脚本很陌生,无法弄清楚如何实现这一点,因此将感谢有关此事的任何帮助。

回答by anubhava

You can do:

你可以做:

# 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

回答by Paul Hicks

Your solution will work for generating the array. Instead of using a while loop, use a for loop:

您的解决方案将用于生成阵列。使用 for 循环而不是使用 while 循环:

#!/bin/bash
files=$( ls * )
counter=0
for i in $files ; do
  echo Next: $i
  let counter=$counter+1
  echo $counter
done