Home > Net >  In bash, how to store top-level dirs in an array for post-processing?
In bash, how to store top-level dirs in an array for post-processing?

Time:11-18

I'm trying to get a list of my top-level dirs in a subdir, so I can post process them, e.g., delete certain ones. I have

# List the top-level dirs and create an array with the resul
DIRS=`ls -1`
IFS=$'\n' read -ra TOP_DIRS <<< "$DIRS"

# Iterate the array
for D in "${TOP_DIRS[@]}"; do
    # For now, just echo the dirs
    echo $D
done

The ls -1 command gives me this for example

00 PRM - AUTO GA
00 PRM - AUTO GA Prod
00 PRM - AUTO GA Prod@script
00 PRM - AUTO GA Prod@script@tmp
00 PRM - AUTO GA STG
00 PRM - AUTO GA STG@script
00 PRM - AUTO GA STG@script@tmp

However, the for loop only echoes the first value, that is

$ ./clean_workspace.sh 
00 PRM - AUTO GA

So obviously my IFS statement is wrong. What am I missing? TIA!

CodePudding user response:

There's no need for ls. Just use a wildcard in an array literal.

top_dirs=(*)

BTW, it's bad style to use uppercase names for your variables. These are conventionally reserved for environment variables.

CodePudding user response:

Just addressing the issue of why OP's current code only processes one directory ...

read is designed to read a single line of input so OP's current code only reads in and stores the first directory:

$ IFS=$'\n' read -ra TOP_DIRS <<< "$DIRS"
$ typeset -p TOP_DIRS
declare -a TOP_DIRS=([0]="00 PRM - AUTO GA")

mapfile is designed to process multiple lines of input, storing each line in a new array entry, eg:

$ mapfile -t TOP_DIRS <<< "$DIRS"
$ typeset -p TOP_DIRS
declare -a TOP_DIRS=([0]="00 PRM - AUTO GA" [1]="00 PRM - AUTO GA Prod" [2]="00 PRM - AUTO GA Prod@script" [3]="00 PRM - AUTO GA Prod@script@tmp" [4]="00 PRM - AUTO GA STG" [5]="00 PRM - AUTO GA STG@script" [6]="00 PRM - AUTO GA STG@script@tmp")

NOTE: this doesn't negate the comment/link about why you shouldn't try to parse ls

  • Related