ls with glob not working in a bash script

Solution 1:

Dennis told you why your script is failing but I'd like to suggest an easier (and safer) way of doing this. Parsing ls is almost always a bad idea, it can easily break on file names with spaces or new lines or other strange characters and is not portable across LOCALE settings. Also, your command is very complex, involving multiple steps. Why not do it all in find?

DIR="/path/to/dirs"
EXCLUDELIST="subdir1,subdir2"
## Build the regular expression
EXCLUDE="${EXCLUDELIST//,/|.*}"
LIST=$(find "$DIR" -type d -regextype posix-awk -not -regex ".*$EXCLUDE.*")

By the way, your script will fail as you have it written because you build the glob before cd-ing into $DIR so it will be built with respect to the contents of your current directory.

Solution 2:

Interactive and non-interactive bash shells do not behave the same. One of the many differences is that the shell option extglob is enabled by default for interactive shells (at least in my version of bash), but not for non-interactive ones.

To fix your script, enable extglob with the following command:

shopt -s extglob