[英]Bash script - how to fill array?
假設我有這個目錄結構:
DIRECTORY:
.........a
.........b
.........c
.........d
我想要做的是:我想將一個目錄的元素存儲在一個數組中
類似於: array = ls /home/user/DIRECTORY
這樣array[0]
包含第一個文件的名稱(即“a”)
array[1] == 'b'
等。
感謝幫助
你不能簡單地做array = ls /home/user/DIRECTORY
,因為 - 即使使用正確的語法 - 它不會給你一個數組,而是一個你必須解析的字符串,並且解析ls
會受到法律的懲罰。 但是,您可以使用內置的 Bash 結構來實現您想要的:
#!/usr/bin/env bash
readonly YOUR_DIR="/home/daniel"
if [[ ! -d $YOUR_DIR ]]; then
echo >&2 "$YOUR_DIR does not exist or is not a directory"
exit 1
fi
OLD_PWD=$PWD
cd "$YOUR_DIR"
i=0
for file in *
do
if [[ -f $file ]]; then
array[$i]=$file
i=$(($i+1))
fi
done
cd "$OLD_PWD"
exit 0
這個小腳本將可以在$YOUR_DIR
找到的所有常規文件的名稱(這意味着沒有目錄、鏈接、套接字等) $YOUR_DIR
到名為array
。
希望這可以幫助。
選項 1,手動循環:
dirtolist=/home/user/DIRECTORY
shopt -s nullglob # In case there aren't any files
contentsarray=()
for filepath in "$dirtolist"/*; do
contentsarray+=("$(basename "$filepath")")
done
shopt -u nullglob # Optional, restore default behavior for unmatched file globs
選項 2,使用 bash 數組技巧:
dirtolist=/home/user/DIRECTORY
shopt -s nullglob
contentspaths=("$dirtolist"/*) # This makes an array of paths to the files
contentsarray=("${contentpaths[@]##*/}") # This strips off the path portions, leaving just the filenames
shopt -u nullglob # Optional, restore default behavior for unmatched file globs
array=($(ls /home/user/DIRECTORY))
然后
echo ${array[0]}
將等於該目錄中的第一個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.