[英]How to list only name of all subfolders under specific folder into a variable using linux bash
我有一个路径./Ur/postProcessing/forces
的文件夹,它包含两个子文件夹名称0
和100
,现在我想将这两个子文件夹的名称列出到一个变量中,例如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) 作为变量? 谢谢!
#!/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"))
要返回一个真正的数组,请参阅: How to return an array in bash without using globals?
您可以在脚本中执行此操作:
# change directory
cd ./Ur/postProcessing/forces/
# read all sub-directories in shell array dirs
dirs=(*/)
# check content of dirs
declare -p dirs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.