Reading filenames into an array

前端 未结 5 2129
青春惊慌失措
青春惊慌失措 2020-11-29 18:30

I want to get a list of files and then read the results into an array where each array element corresponds to a file name. Is this possible?

5条回答
  •  时光说笑
    2020-11-29 19:08

    Actually, ls isn't the way to go. Try this:

    declare -a FILELIST
    for f in *; do 
        #FILELIST[length_of_FILELIST + 1]=filename
        FILELIST[${#FILELIST[@]}+1]=$(echo "$f");
    done
    

    To get a filename from the array use:

    echo ${FILELIST[x]}
    

    To get n filenames from the array starting from x use:

    echo ${FILELIST[@]:x:n}
    

    For a great tutorial on bash arrays, see: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

提交回复
热议问题