Home > database >  How to list only name of all subfolders under specific folder into a variable using linux bash
How to list only name of all subfolders under specific folder into a variable using linux bash

Time:05-17

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!

CodePudding user response:

#!/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?

CodePudding user response:

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
  • Related