如何使用 linux bash 将特定文件夹下所有子文件夹的名称仅列出到变量中
How to list only name of all subfolders under specific folder into a variable using linux bash
我有一个路径为 ./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) 作为变量?谢谢!
您可以在脚本中执行此操作:
# change directory
cd ./Ur/postProcessing/forces/
# read all sub-directories in shell array dirs
dirs=(*/)
# check content of dirs
declare -p dirs
#!/bin/bash
get_times()( # sub-shell so don't need to cd back nor use local
if cd ""; 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"))
要return一个真正的数组,见:How to return an array in bash without using globals?
我有一个路径为 ./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) 作为变量?谢谢!
您可以在脚本中执行此操作:
# change directory
cd ./Ur/postProcessing/forces/
# read all sub-directories in shell array dirs
dirs=(*/)
# check content of dirs
declare -p dirs
#!/bin/bash
get_times()( # sub-shell so don't need to cd back nor use local
if cd ""; 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"))
要return一个真正的数组,见:How to return an array in bash without using globals?