I need to write some shell script to get all the directory that start with certain letters and save the result list in a txt file


-all uppercase directory

-all directory that starts with "Ab"

Any suggestion?


1 Answer 1


All uppercase directories:

shopt -s nullglob
for d in [[:upper:]]*/ ; do
    echo "$d"
done > uppercase-dirs.txt

All directories starting with Ab:

shopt -s nullglob
for d in Ab*/ ; do
    echo "$d"
done > Ab-dirs.txt

For more info see the pattern matching section of the bash manual.

Note you may have directories that contain unusual characters, e.g. newline. In which case echoing each directory to a text file as a new line will give you incorrect results. One way to get around that is to instead use the nul character to separate each directory. You could do this using printf instead:

shopt -s nullglob
for d in Ab*/ ; do
     printf "%s\0" "$d"

Note also that the shopt -s nullglob is necessary to handle the case when there are no matches to the pattern. Without it, Ab*/ would expand to Ab*/ if there were no matches which is not what you want here. With it, Ab*/ expands to the empty string if there were no matches.

For more information see the shopt section of the bash manual.

  • Just a little clarification... what is the purpose of shopt in this situation?
    – AndreaF
    Feb 17, 2015 at 2:14
  • @AndreaF Clarification added. Feb 17, 2015 at 2:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .