我試圖在子目錄中獲取我的頂級目錄串列,以便我可以對它們進行后處理,例如,洗掉某些目錄。我有
# List the top-level dirs and create an array with the resul
DIRS=`ls -1`
IFS=$'\n' read -ra TOP_DIRS <<< "$DIRS"
# Iterate the array
for D in "${TOP_DIRS[@]}"; do
# For now, just echo the dirs
echo $D
done
例如,ls -1命令給了我這個
00 PRM - AUTO GA
00 PRM - AUTO GA Prod
00 PRM - AUTO GA Prod@script
00 PRM - AUTO GA Prod@script@tmp
00 PRM - AUTO GA STG
00 PRM - AUTO GA STG@script
00 PRM - AUTO GA STG@script@tmp
但是,for回圈只回顯第一個值,即
$ ./clean_workspace.sh
00 PRM - AUTO GA
所以很明顯我的IFS說法是錯誤的。我錯過了什么?TIA!
uj5u.com熱心網友回復:
沒有必要ls。只需在陣列文字中使用通配符。
top_dirs=(*)
順便說一句,為變數使用大寫名稱是不好的風格。這些通常是為環境變數保留的。
uj5u.com熱心網友回復:
只是解決為什么 OP 當前代碼只處理一個目錄的問題......
read旨在讀取單行輸入,因此 OP 的當前代碼僅讀取并存盤第一個目錄:
$ IFS=$'\n' read -ra TOP_DIRS <<< "$DIRS"
$ typeset -p TOP_DIRS
declare -a TOP_DIRS=([0]="00 PRM - AUTO GA")
mapfile旨在處理多行輸入,將每一行存盤在一個新的陣列條目中,例如:
$ mapfile -t TOP_DIRS <<< "$DIRS"
$ typeset -p TOP_DIRS
declare -a TOP_DIRS=([0]="00 PRM - AUTO GA" [1]="00 PRM - AUTO GA Prod" [2]="00 PRM - AUTO GA Prod@script" [3]="00 PRM - AUTO GA Prod@script@tmp" [4]="00 PRM - AUTO GA STG" [5]="00 PRM - AUTO GA STG@script" [6]="00 PRM - AUTO GA STG@script@tmp")
注意:這不會否定關于為什么你不應該嘗試決議的評論/鏈接ls
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/536285.html
標籤:狂欢壳
上一篇:使用shell洗掉列中的重復字串
下一篇:Bash提取json的第一個鍵
