我有一個帶有 path 的檔案夾./Ur/postProcessing/forces,它包含兩個 sub_folders 名稱0和100,現在我想將這兩個 sub_folders 的名稱列出到一個變數中,例如time=(0 100).
我的代碼是
dirs=(./Ur/postProcessing/forces/*/)
timeDirs=$(for dir in "${dirs[@]}"
do
echo "$dir"
done)
echo "$timeDirs"
我得到以下結果:
./Ur/postProcessing/forcs/0/
./Ur/postProcessing/forces/100/
如何獲得 (0 100) 作為變數?謝謝!
uj5u.com熱心網友回復:
#!/bin/bash
get_times()( # sub-shell so don't need to cd back nor use local
if cd "$1"; then
# collect directories
dirs=(*/)
# strip trailing slashes and display
echo "${dirs[@]%/}"
fi
)
dir="./Ur/postProcessing/forces"
# assign into simple variable
timeStr="($(get_times "$dir"))"
# or assign into array
# (only works if get_times output is whitespace-delimited)
timeList=($(get_times "$dir"))
要回傳一個真正的陣列,請參閱:如何在不使用全域變數的情況下在 bash 中回傳一個陣列?
uj5u.com熱心網友回復:
您可以在腳本中執行此操作:
# change directory
cd ./Ur/postProcessing/forces/
# read all sub-directories in shell array dirs
dirs=(*/)
# check content of dirs
declare -p dirs
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476209.html
上一篇:Unix上的檔案計數
