0

I am trying to list all files located in specific sub-directories of a directory in my bash script. Here is what I tried.

root_dir="/home/shaf/data/"
sub_dirs_prefixes=('ab' 'bp' 'cd' 'cn' 'll' 'mr' 'mb' 'nb' 'nh' 'nw' 'oh' 'st' 'wh')

ls "$root_dir"{$(IFS=,; echo "${sub_dirs_prefixes[*]}")}"rrc/"

Please note that I do not want to expand value stored in $root_dir as it may contain spaces but I do want to expand sub-path contained in {} which is a comma delimited string of contents of $sub_dirs_prefixes. I stored sub-directories prefixes in an array variable, $sub_dirs_prefixes , because I have to use them later on for something else.

I am getting following error:

ls: cannot access /home/shaf/data/{ab,bp,cd,cn,ll,mr,mb,nb,nh,nw,oh,st,wh}rrc/

If I copy the path in error message and run ls from command line, it does display contents of listed sub-directories.

1
  • 1
    Brace expansion happens before variable expansion, so this isn't possible in one pass. You could eval with all the security/reliability implications that has, but you'd be better off using a loop or array substitution. Commented Dec 9, 2016 at 19:42

1 Answer 1

1

You can command substitution to generate an extended pattern.

shopt -s extglob
ls "$root_dir"/$(IFS="|"; echo "@(${sub_dirs_prefixes[*]})rrc")

By the time parameter can command substitutions have completed, the shell sees this just before performing pathname expansion:

ls "/home/shaf/data/"/@(ab|bp|cd|cn|ll|mr|mb|nb|nh|nw|oh|st|wh)rrc

The @(...) pattern matches one of the enclosed prefixes.

It gets a little trickier if the components of the directory names contain characters that need to be quoted, since we aren't quoting the command substitution.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Can you please explain a little how extglob works so that i can accept your answer? Also you may want to remove / before @. You said @ matches one of the enclosed prefixes even though it matches each of those when I tried and returning correct result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.