shell 將文件名讀入數組
我想得到一個文件列表,然后將結果讀入一個數組,其中每個數組元素對應一個文件名。
shopt -s nullglob
array=(*)
array2=(file*)
array3=(dir/*)
如果沒有匹配項,則nullglob選項會使數組為空。
以下將在當前目錄中創建一個帶ls輸出的數組arr:
arr=( $(ls) )
雖然使用ls的輸出根本不安全。
比ls更好更安全,你可以使用echo *:
arr=( * )
echo ${#arr[@]} # will echo number of elements in array
echo "${arr[@]}" # will dump all elements of the array
path="" # could set to any absolute path
declare -a array=( "${path}"/* )