1

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!

WUYing
  • 71
  • 5

2 Answers2

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

jhnc
  • 11,310
  • 1
  • 9
  • 26
0

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
anubhava
  • 761,203
  • 64
  • 569
  • 643