'How to list only name of all subfolders under specific folder into a variable using linux bash
I have a folder with path ./Ur/postProcessing/forces, and it includes two sub_folders name 0 and 100, now I want to list the name of these two sub_folders into a variable, like time=(0 100).
My code is
dirs=(./Ur/postProcessing/forces/*/)
timeDirs=$(for dir in "${dirs[@]}"
do
echo "$dir"
done)
echo "$timeDirs"
And I get the following results:
./Ur/postProcessing/forcs/0/
./Ur/postProcessing/forces/100/
How can I get (0 100) as a variable? Thanks!
Solution 1:[1]
You can do this in your scripts:
# change directory
cd ./Ur/postProcessing/forces/
# read all sub-directories in shell array dirs
dirs=(*/)
# check content of dirs
declare -p dirs
Solution 2:[2]
#!/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"))
To return a real array, see: How to return an array in bash without using globals?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anubhava |
| Solution 2 | jhnc |
