🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 18 (from laksa151)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
15 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.5 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash
Last Crawled2026-04-07 01:01:04 (15 days ago)
First Indexed2015-03-23 11:21:03 (11 years ago)
HTTP Status Code200
Content
Meta Titlefiles - How do I loop through only directories in bash? - Unix & Linux Stack Exchange
Meta Descriptionnull
Meta Canonicalnull
Boilerpipe Text
This answer is assuming that all that needs to be done is to find the sub-directories of some top-level directory. For an answer specific to bash (and to some degree, the zsh shell), see the second part of rubo77's wiki answer , where dotglob and nullglob is being used to correctly loop over the directories (or symbolic links to directories) in a single directory. For a portable solution that does not depend on bash for doing the actual selection of files, you may use find to loop over all directories in some top-level directory like so: topdir=. find " $topdir " ! -path " $topdir " -prune - type d - exec sh -c ' for dirpath do # user code goes here, using "$dirpath" printf "\"%s\" is a directory\n" "$dirpath" done' sh {} + The above code assumes that the top directory that we're interested in is the current directory ( . ). Set topdir to some other pathname to use it on another directory. The find utility is asked to ignore pathnames that are identical to the starting search path with ! -path "$topdir" , and then to prune (not enter) any other pathnames found. This limits the search to only the directory referenced by $topdir . Pathnames that are directories ( -type d ) are collected and a sh -c script is executed with batches of these as arguments. The sh -c script is the code that we'd like to execute on all the directories, so it iterates over its given arguments and does whatever it needs to do with each of them. If you need to do something that requires bash , you would obviously use bash -c instead. The sh -c script could be separated out into its own script like so: #!/bin/sh for dirpath do # user code goes here, using "$dirpath" printf '"%s" is a directory\n' " $dirpath " done ... which would be called from find like so: find " $topdir " ! -path " $topdir " -prune - type d - exec ./myscript.sh {} + See also: Understanding the -exec option of `find`
Markdown
# ![site logo](https://stackoverflow.com/Content/Img/SE-logo75.png) By clicking “Sign up”, you agree to our [terms of service](https://unix.stackexchange.com/legal/terms-of-service/public) and acknowledge you have read our [privacy policy](https://unix.stackexchange.com/legal/privacy-policy). # OR Already have an account? [Log in](https://unix.stackexchange.com/users/login) [Skip to main content](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#content) #### Stack Exchange Network Stack Exchange network consists of 183 Q\&A communities including [Stack Overflow](https://stackoverflow.com/), the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. [Visit Stack Exchange](https://stackexchange.com/) 1. - [Tour Start here for a quick overview of the site](https://unix.stackexchange.com/tour) - [Help Center Detailed answers to any questions you might have](https://unix.stackexchange.com/help) - [Meta Discuss the workings and policies of this site](https://unix.meta.stackexchange.com/) - [About Us Learn more about Stack Overflow the company, and our products](https://stackoverflow.co/) 2. ### [current community](https://unix.stackexchange.com/) - [Unix & Linux](https://unix.stackexchange.com/) [help](https://unix.stackexchange.com/help) [chat](https://chat.stackexchange.com/?tab=site&host=unix.stackexchange.com) - [Unix & Linux Meta](https://unix.meta.stackexchange.com/) ### your communities [Sign up](https://unix.stackexchange.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Funix.stackexchange.com%2Fquestions%2F86722%2Fhow-do-i-loop-through-only-directories-in-bash) or [log in](https://unix.stackexchange.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Funix.stackexchange.com%2Fquestions%2F86722%2Fhow-do-i-loop-through-only-directories-in-bash) to customize your list. ### [more stack exchange communities](https://stackexchange.com/sites) [company blog](https://stackoverflow.blog/) 3. [Log in](https://unix.stackexchange.com/users/login?ssrc=head&returnurl=https%3A%2F%2Funix.stackexchange.com%2Fquestions%2F86722%2Fhow-do-i-loop-through-only-directories-in-bash) 4. [Sign up](https://unix.stackexchange.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Funix.stackexchange.com%2Fquestions%2F86722%2Fhow-do-i-loop-through-only-directories-in-bash) [![Unix & Linux](https://unix.stackexchange.com/Content/Sites/unix/Img/logo.svg?v=eb6eb2b9e73c)](https://unix.stackexchange.com/) 1. 1. [Home](https://unix.stackexchange.com/) 2. [Questions](https://unix.stackexchange.com/questions) 3. [Unanswered](https://unix.stackexchange.com/unanswered) 4. [AI Assist](https://stackoverflow.com/ai-assist) 5. [Tags](https://unix.stackexchange.com/tags) 6. [Chat](https://chat.stackexchange.com/) 7. [Users](https://unix.stackexchange.com/users) 8. [Companies](https://stackoverflow.com/jobs/companies?so_medium=unix&so_source=SiteNav) 2. Stack Internal Stack Overflow for Teams is now called **Stack Internal**. Bring the best of human thought and AI automation together at your work. [Try for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=unix-community&utm_campaign=side-bar&utm_content=explore-teams) [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=unix-community&utm_campaign=side-bar&utm_content=explore-teams) 3. [Stack Internal]() 4. Bring the best of human thought and AI automation together at your work. [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=unix-community&utm_campaign=side-bar&utm_content=explore-teams-compact) **Stack Internal** Knowledge at work Bring the best of human thought and AI automation together at your work. [Explore Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=unix-community&utm_campaign=side-bar&utm_content=explore-teams-compact-popover) # [How do I loop through only directories in bash?](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash) [Ask Question](https://unix.stackexchange.com/questions/ask) Asked 12 years, 7 months ago Modified [4 years, 6 months ago](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash?lastactivity "2021-09-09 06:24:55Z") Viewed 934k times This question shows research effort; it is useful and clear 540 Save this question. Show activity on this post. I have a folder with some directories and some files (some are hidden, beginning with dot). ``` for d in *; do echo $d done ``` will loop through all files and directories, but I want to loop only through directories. How do I do that? - [bash](https://unix.stackexchange.com/questions/tagged/bash "show questions tagged 'bash'") - [files](https://unix.stackexchange.com/questions/tagged/files "show questions tagged 'files'") - [directory](https://unix.stackexchange.com/questions/tagged/directory "show questions tagged 'directory'") [Share](https://unix.stackexchange.com/q/86722 "Short permalink to this question") Share a link to this question Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this question](https://unix.stackexchange.com/posts/86722/edit) Follow Follow this question to receive notifications [edited Jan 26, 2021 at 19:07](https://unix.stackexchange.com/posts/86722/revisions "show all edits to this post") asked Aug 14, 2013 at 15:43 [![rubo77's user avatar](https://www.gravatar.com/avatar/39a2a1be687c3e1088300dc7782a7f12?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/20661/rubo77) [rubo77](https://unix.stackexchange.com/users/20661/rubo77) 30\.7k4646 gold badges143143 silver badges218218 bronze badges 0 [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \| ## 14 Answers 14 Sorted by: [Reset to default](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash?answertab=scoredesc#tab-top) This answer is useful 737 Save this answer. Show activity on this post. You can specify a slash at the end to match only directories: ``` for d in */ ; do echo "$d" done ``` If you want to exclude symlinks, use a test to `continue` the loop if the current entry is a link. You need to remove the trailing slash from the name in order for `-L` to be able to recognise it as a symbolic link: ``` for d in */ ; do [ -L "${d%/}" ] && continue echo "$d" done ``` [Share](https://unix.stackexchange.com/a/86724 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/86724/edit) Follow Follow this answer to receive notifications [edited Sep 9, 2021 at 6:24](https://unix.stackexchange.com/posts/86724/revisions "show all edits to this post") [![Stéphane Chazelas's user avatar](https://i.sstatic.net/BkKfT.png?s=64)](https://unix.stackexchange.com/users/22565/st%C3%A9phane-chazelas) [Stéphane Chazelas](https://unix.stackexchange.com/users/22565/st%C3%A9phane-chazelas) 592k9797 gold badges1\.1k1\.1k silver badges1\.7k1\.7k bronze badges answered Aug 14, 2013 at 15:46 [![choroba's user avatar](https://www.gravatar.com/avatar/957956ce51706d03f19a4dc85a767bb1?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/13792/choroba) [choroba](https://unix.stackexchange.com/users/13792/choroba) 49\.7k77 gold badges9393 silver badges119119 bronze badges 8 - 2 You can loop through hidden files too with `for d in */ .*/ : do ...`. But how do I loop through hidden files excluding `../`? rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-21 03:12:59 +00:00 [Commented Oct 21, 2013 at 3:12](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147111_86724) - 1 @AsymLabs That's incorrect, `set -P` only affects commands which change directory. [sprunge.us/TNac](http://sprunge.us/TNac) Chris Down – [Chris Down](https://unix.stackexchange.com/users/10762/chris-down "130,681 reputation") 2013-10-22 06:14:06 +00:00 [Commented Oct 22, 2013 at 6:14](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147443_86724) - 1 Can someone explain the `*/ ;` a little more? I am having trouble understanding exactly that the code is/does. timbram – [timbram](https://unix.stackexchange.com/users/116191/timbram "151 reputation") 2017-07-28 15:22:11 +00:00 [Commented Jul 28, 2017 at 15:22](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment679631_86724) - 3 @timbram: `*` is a wildcard, it stands for "anything". `/` means the "anything" must be a directory in order to match the wildcard expression. `;` is part of the for loop, it separates the `do` from the `for`. choroba – [choroba](https://unix.stackexchange.com/users/13792/choroba "49,741 reputation") 2017-07-28 16:11:25 +00:00 [Commented Jul 28, 2017 at 16:11](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment679655_86724) - 3 Add `shopt -s nullglob` to prevent problems if there is no directory in the current folder rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2018-09-24 04:59:51 +00:00 [Commented Sep 24, 2018 at 4:59](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment859416_86724) \| [Show **3** more comments](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Expand to show all comments on this post") This answer is useful 140 Save this answer. Show activity on this post. You can test with `-d`: ``` for f in *; do if [ -d "$f" ]; then # $f is a directory fi done ``` This is one of the [file test operators](http://www.tldp.org/LDP/abs/html/fto.html). [Share](https://unix.stackexchange.com/a/86727 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/86727/edit) Follow Follow this answer to receive notifications [edited Apr 4, 2019 at 8:35](https://unix.stackexchange.com/posts/86727/revisions "show all edits to this post") answered Aug 14, 2013 at 15:59 [![goldilocks's user avatar](https://i.sstatic.net/q6fMI.jpg?s=64)](https://unix.stackexchange.com/users/25985/goldilocks) [goldilocks](https://unix.stackexchange.com/users/25985/goldilocks) 90\.3k3333 gold badges212212 silver badges274274 bronze badges 4 - 10 Note that it will include symlinks to directories. Stéphane Chazelas – [Stéphane Chazelas](https://unix.stackexchange.com/users/22565/st%C3%A9phane-chazelas "592,180 reputation") 2013-08-14 16:12:22 +00:00 [Commented Aug 14, 2013 at 16:12](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment129230_86727) - 35 `if [[ -d "$f" && ! -L "$f" ]]` will exclude symlinks rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-22 06:33:52 +00:00 [Commented Oct 22, 2013 at 6:33](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147447_86727) - 1 Will break on empty directory. `if [[ "$f" = "*" ]]; then continue; fi` Piskvor – [Piskvor](https://unix.stackexchange.com/users/5477/piskvor "702 reputation") 2019-04-01 09:02:32 +00:00 [Commented Apr 1, 2019 at 9:02](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment942227_86727) - @Piskvorleftthebuilding If the current directory is empty, the `-d` test will be false, so no worries and you don't have to compare against the pattern. Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-01-26 19:31:06 +00:00 [Commented Jan 26, 2021 at 19:31](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1181140_86727) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 75 Save this answer. Show activity on this post. Beware that choroba's solution, though elegant, can elicit unexpected behavior if no directories are available within the current directory. In this state, rather than skipping the `for` loop, bash will run the loop exactly once where `d` is equal to `*/`: ``` #!/usr/bin/env bash for d in */; do # Will print */ if no directories are available echo "$d" done ``` I recommend using the following to protect against this case: ``` #!/usr/bin/env bash for f in *; do if [ -d "$f" ]; then # Will not run if no directories are available echo "$f" fi done ``` This code will loop through all files in the current directory, check if `f` is a directory, then echo `f` if the condition returns true. If `f` is equal to `*/`, `echo "$f"` will not execute. [Share](https://unix.stackexchange.com/a/218522 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/218522/edit) Follow Follow this answer to receive notifications [edited Jun 9, 2020 at 8:00](https://unix.stackexchange.com/posts/218522/revisions "show all edits to this post") [![Chris Davies's user avatar](https://i.sstatic.net/Kdqk1.jpg?s=64)](https://unix.stackexchange.com/users/100397/chris-davies) [Chris Davies](https://unix.stackexchange.com/users/100397/chris-davies) 129k1616 gold badges180180 silver badges328328 bronze badges answered Jul 26, 2015 at 23:54 [![emagdne's user avatar](https://www.gravatar.com/avatar/a6327cd2881cd447763ea609671f20d6?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/125079/emagdne) [emagdne](https://unix.stackexchange.com/users/125079/emagdne) 85166 silver badges44 bronze badges 1 - 12 Much easier to `shopt -s nullglob`. choroba – [choroba](https://unix.stackexchange.com/users/13792/choroba "49,741 reputation") 2016-06-23 07:14:42 +00:00 [Commented Jun 23, 2016 at 7:14](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment510414_218522) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 35 Save this answer. Show activity on this post. If you need to select more specific files than only directories use `find` and pass it to `while read`: ``` shopt -s dotglob find * -prune -type d | while IFS= read -r d; do echo "$d" done ``` Use `shopt -u dotglob` to exclude hidden directories (or `setopt dotglob`/`unsetopt dotglob` in zsh). `IFS=` to avoid splitting filenames containing one of the `$IFS`, for example: `'a b'` see [AsymLabs answer](https://unix.stackexchange.com/a/96912/20661) below for more `find` options *** edit: In case you need to create an exit value from within the while loop, you can circumvent the extra subshell by this trick: ``` while IFS= read -r d; do if [ "$d" == "something" ]; then exit 1; fi done < <(find * -prune -type d) ``` [Share](https://unix.stackexchange.com/a/97074 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/97074/edit) Follow Follow this answer to receive notifications [edited Jul 7, 2017 at 7:10](https://unix.stackexchange.com/posts/97074/revisions "show all edits to this post") answered Oct 22, 2013 at 4:50 [![rubo77's user avatar](https://www.gravatar.com/avatar/39a2a1be687c3e1088300dc7782a7f12?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/20661/rubo77) [rubo77](https://unix.stackexchange.com/users/20661/rubo77) 30\.7k4646 gold badges143143 silver badges218218 bronze badges 6 - 3 I found this solution on: [stackoverflow.com/a/8489394/1069083](http://stackoverflow.com/a/8489394/1069083) rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-22 05:06:51 +00:00 [Commented Oct 22, 2013 at 5:06](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147435_97074) - 1 [Don't loop over the output of `find`](https://unix.stackexchange.com/questions/321697). It doesn't matter that you set `IFS` to an empty string, it will still break on filenames containing newlines. It doesn't matter that these filenames are rare, if it's easy to write code that copes with *all* filenames, then there's no reason to write code that doesn't. Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-01-26 19:32:19 +00:00 [Commented Jan 26, 2021 at 19:32](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1181143_97074) - @Kusalananda "Don't loop over the output of `find`" is misleading. It is fine, provided that output elements are not line-terminated (the default), rather null-terminated. This would require changing the IFS to the 0-byte OR making `read` handle it with `read -d`. Then even filenames containing newlines would be processed correctly. Jonathan Komar – [Jonathan Komar](https://unix.stackexchange.com/users/33386/jonathan-komar "7,164 reputation") 2021-03-04 06:49:40 +00:00 [Commented Mar 4, 2021 at 6:49](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1194440_97074) - @JonathanKomar It is not misleading as none of the precautions are taken in this answer. Changing `IFS` to contain a nul character implies a shell that can store these in variables. The `bash` shell does not do that. `read -d` is `bash`\-specific (`xargs -0` would be a better fit as it isn't dependent on the shell, even though it's still not standard). My point is that if you can do it right, in a way that is portable and safe, then there is no reason to make it unportable and/or unsafe. `find` has `-exec` for the very reason to provide a way to iterate over found pathnames with user code\! Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-03-04 08:10:46 +00:00 [Commented Mar 4, 2021 at 8:10](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1194450_97074) - @kusalananda: please provide a separate answer with your solution, so we can upvote it rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-03-04 08:31:34 +00:00 [Commented Mar 4, 2021 at 8:31](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1194453_97074) \| [Show **1** more comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Expand to show all comments on this post") This answer is useful 15 Save this answer. Show activity on this post. You can use pure bash for that, but it's better to use find: ``` find . -maxdepth 1 -type d -exec echo {} \; ``` (find additionally will include hidden directories) [Share](https://unix.stackexchange.com/a/86725 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/86725/edit) Follow Follow this answer to receive notifications answered Aug 14, 2013 at 15:46 [![rush's user avatar](https://www.gravatar.com/avatar/95bbd370e761f3b28d29df62c74ea5e9?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/13003/rush) [rush](https://unix.stackexchange.com/users/13003/rush) 28\.1k99 gold badges9292 silver badges115115 bronze badges 2 - 10 Note that it doesn't include symlinks to directories. You can use `shopt -s dotglob` for `bash` to include hidden directories. Yours will also include `.`. Also note that `-maxdepth` is not a standard option (`-prune` is). Stéphane Chazelas – [Stéphane Chazelas](https://unix.stackexchange.com/users/22565/st%C3%A9phane-chazelas "592,180 reputation") 2013-08-14 16:11:47 +00:00 [Commented Aug 14, 2013 at 16:11](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment129229_86725) - 3 The `dotglob` option is interesting but `dotglob` only applies to the use of `*`. `find .` will always include hidden directories (and the current dir as well) rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-22 05:28:45 +00:00 [Commented Oct 22, 2013 at 5:28](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147436_86725) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 9 Save this answer. Show activity on this post. This is done to find both visible and hidden directories within the present working directory, excluding the root directory: to just loop through directories: ``` find -path './*' -prune -type d ``` to include symlinks in the result: ``` find -L -path './*' -prune -type d ``` to do something to each directory (excluding symlinks): ``` find -path './*' -prune -type d -print0 | xargs -0 <cmds> ``` to exclude hidden directories: ``` find -path './[^.]*' -prune -type d ``` to execute multiple commands on the returned values (a very contrived example): ``` find -path './[^.]*' -prune -type d -print0 | xargs -0 -I '{}' sh -c \ "printf 'first: %-40s' '{}'; printf 'second: %s\n' '{}'" ``` instead of 'sh -c' can also use 'bash -c', etc. [Share](https://unix.stackexchange.com/a/96912 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/96912/edit) Follow Follow this answer to receive notifications [edited Oct 22, 2013 at 5:11](https://unix.stackexchange.com/posts/96912/revisions "show all edits to this post") [![rubo77's user avatar](https://www.gravatar.com/avatar/39a2a1be687c3e1088300dc7782a7f12?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/20661/rubo77) [rubo77](https://unix.stackexchange.com/users/20661/rubo77) 30\.7k4646 gold badges143143 silver badges218218 bronze badges answered Oct 21, 2013 at 3:47 [![AsymLabs's user avatar](https://www.gravatar.com/avatar/d16460cc1c56393073604f1b85241818?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/48896/asymlabs) [AsymLabs](https://unix.stackexchange.com/users/48896/asymlabs) 2,76711 gold badge1414 silver badges1111 bronze badges 14 - What happens if the echo '\*/' in 'for d in echo \*/' contains, say, 60,000 directories? AsymLabs – [AsymLabs](https://unix.stackexchange.com/users/48896/asymlabs "2,767 reputation") 2013-10-21 04:05:03 +00:00 [Commented Oct 21, 2013 at 4:05](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147118_96912) - You will get "Too many files" error but that can be solved: [How to circumvent “Too many open files” in debian](http://unix.stackexchange.com/questions/85457/how-to-circumvent-too-many-open-files-in-debian) rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-21 04:09:55 +00:00 [Commented Oct 21, 2013 at 4:09](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147119_96912) - 1 The xargs example only would works for a subset of directory names 9e.g. those with spaces or newlines would not work). Better to use `... -print0 | xargs -0 ...` if you don't know what the exact names are. Anthon – [Anthon](https://unix.stackexchange.com/users/33055/anthon "81,513 reputation") 2013-10-21 04:50:18 +00:00 [Commented Oct 21, 2013 at 4:50](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147133_96912) - 1 @rubo77 added way to exclude hidden files/directories and execution of multiple commands - of course this can be done with a script too. AsymLabs – [AsymLabs](https://unix.stackexchange.com/users/48896/asymlabs "2,767 reputation") 2013-10-21 11:22:22 +00:00 [Commented Oct 21, 2013 at 11:22](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147191_96912) - 2 I added an example in my answer at the bottom, how to do something to each directory using a function with `find * | while read file; do ...` rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2013-10-22 04:37:27 +00:00 [Commented Oct 22, 2013 at 4:37](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment147433_96912) \| [Show **9** more comments](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Expand to show all comments on this post") This answer is useful 4 Save this answer. Show activity on this post. You can loop through all directories including hidden directories (beginning with a dot) in one line and multiple commands with: ``` for name in */ .*/ ; do printf '%s is a directory\n' "$name"; done ``` If you want to exclude symbolic links: ``` for name in *; do if [ -d "$name" ] && [ ! -L "$name" ]; then printf '%s is a directory\n' "$name" fi done ``` Note: *Using the list `*/ .*/` works in `bash`, but also displays the folders `.` and `..` while in `zsh` it will not show these but throw an error if there is no hidden file in the folder* *** A cleaner version that will include hidden directories and exclude `../` will be with the `dotglob` shell option in `bash`: ``` shopt -s dotglob nullglob for name in */ ; do printf '%s is a directory\n' "$name"; done ``` The `nullglob` shell option makes the pattern disappear completely (instead of remaining unexpanded) if no name matches it. (Use the pattern `*(ND/)` in the `zsh` shell; the `/` makes the preceding `*` match only directories, and the `ND` makes it act as if both `nullglob` and `dotglob` were set) You may unset `dotglob` and `nullglob` with ``` shopt -u dotglob nullglob ``` [Share](https://unix.stackexchange.com/a/96904 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/96904/edit) Follow Follow this answer to receive notifications [edited Mar 4, 2021 at 8:30](https://unix.stackexchange.com/posts/96904/revisions "show all edits to this post") community wiki [12 revs, 2 users 82%](https://unix.stackexchange.com/posts/96904/revisions "show revision history for this post") [rubo77](https://unix.stackexchange.com/users/20661) 0 [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 2 Save this answer. Show activity on this post. Use `find` with `-exec` to loop through the directories and call a **function** in the exec option: ``` dosomething () { echo "doing something with $1" } export -f dosomething find ./* -prune -type d -exec bash -c 'dosomething "$0"' {} \; ``` Use `shopt -s dotglob` or `shopt -u dotglob` to include/exclude hidden directories [Share](https://unix.stackexchange.com/a/97083 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/97083/edit) Follow Follow this answer to receive notifications [edited Mar 6, 2021 at 13:45](https://unix.stackexchange.com/posts/97083/revisions "show all edits to this post") answered Oct 22, 2013 at 6:26 [![rubo77's user avatar](https://www.gravatar.com/avatar/39a2a1be687c3e1088300dc7782a7f12?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/20661/rubo77) [rubo77](https://unix.stackexchange.com/users/20661/rubo77) 30\.7k4646 gold badges143143 silver badges218218 bronze badges 4 - The `nullglob` and `dotglob` shell options would unfortunately not make any difference here as the shell is never used for doing globbing. The `-path './*'` test would be true for all pathnames as all are found under the `.` directory (the default search path with GNU `find` if no search path is given). Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-03-04 09:11:25 +00:00 [Commented Mar 4, 2021 at 9:11](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1194466_97083) - Thx, I removed the`-path` rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-03-06 12:23:35 +00:00 [Commented Mar 6, 2021 at 12:23](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1195153_97083) - Well, now it would look in a directory called `*` in the current directory (due to the quoting). Removing the single quotes would make it search each non-hidden name in the current directory. You probably want just `.` instead. Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-03-06 12:33:41 +00:00 [Commented Mar 6, 2021 at 12:33](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1195154_97083) - 1 Thx, I removed the single quotes. I think now the `dotglob` option would be effective rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-03-06 13:46:27 +00:00 [Commented Mar 6, 2021 at 13:46](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1195165_97083) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 1 Save this answer. Show activity on this post. This will include the complete path in each directory in the list: ``` for i in $(find $PWD -maxdepth 1 -type d); do echo $i; done ``` [Share](https://unix.stackexchange.com/a/97076 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/97076/edit) Follow Follow this answer to receive notifications [edited Oct 27, 2013 at 23:31](https://unix.stackexchange.com/posts/97076/revisions "show all edits to this post") [![rubo77's user avatar](https://www.gravatar.com/avatar/39a2a1be687c3e1088300dc7782a7f12?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/20661/rubo77) [rubo77](https://unix.stackexchange.com/users/20661/rubo77) 30\.7k4646 gold badges143143 silver badges218218 bronze badges answered Oct 22, 2013 at 5:16 user26053 1 - 6 breaks when using folders with spaces Alejandro Sazo – [Alejandro Sazo](https://unix.stackexchange.com/users/38118/alejandro-sazo "101 reputation") 2016-10-24 02:15:39 +00:00 [Commented Oct 24, 2016 at 2:15](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment559586_97076) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 1 Save this answer. Show activity on this post. This answer is assuming that *all* that needs to be done is to find the sub-directories of some top-level directory. For an answer specific to `bash` (and to some degree, the `zsh` shell), see the second part of [rubo77's wiki answer](https://unix.stackexchange.com/a/96904/116858), where `dotglob` and `nullglob` is being used to correctly loop over the directories (or symbolic links to directories) in a single directory. For a portable solution that does not depend on `bash` for doing the actual selection of files, you may use `find` to loop over all directories in some top-level directory like so: ``` topdir=. find "$topdir" ! -path "$topdir" -prune -type d -exec sh -c ' for dirpath do # user code goes here, using "$dirpath" printf "\"%s\" is a directory\n" "$dirpath" done' sh {} + ``` The above code assumes that the top directory that we're interested in is the current directory (`.`). Set `topdir` to some other pathname to use it on another directory. The `find` utility is asked to ignore pathnames that are identical to the starting search path with `! -path "$topdir"`, and then to prune (not enter) any other pathnames found. This limits the search to only the directory referenced by `$topdir`. Pathnames that are directories (`-type d`) are collected and a `sh -c` script is executed with batches of these as arguments. The `sh -c` script is the code that we'd like to execute on all the directories, so it iterates over its given arguments and does whatever it needs to do with each of them. If you need to do something that requires `bash`, you would obviously use `bash -c` instead. The `sh -c` script could be separated out into its own script like so: ``` #!/bin/sh for dirpath do # user code goes here, using "$dirpath" printf '"%s" is a directory\n' "$dirpath" done ``` ... which would be called from `find` like so: ``` find "$topdir" ! -path "$topdir" -prune -type d -exec ./myscript.sh {} + ``` See also: - [Understanding the -exec option of \`find\`](https://unix.stackexchange.com/questions/389705) [Share](https://unix.stackexchange.com/a/637522 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/637522/edit) Follow Follow this answer to receive notifications [edited Mar 4, 2021 at 9:03](https://unix.stackexchange.com/posts/637522/revisions "show all edits to this post") answered Mar 4, 2021 at 8:54 [![Kusalananda's user avatar](https://i.sstatic.net/TMLpwitJ.png?s=64)](https://unix.stackexchange.com/users/116858/kusalananda) [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda)♦ 358k4242 gold badges743743 silver badges1\.1k1\.1k bronze badges 2 - You could use `find "$topdir"/*` without `! -path "$topdir"` rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-03-06 12:20:27 +00:00 [Commented Mar 6, 2021 at 12:20](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1195152_637522) - @rubo77 Doing that would make it search all the pathnames matching `"$topdir"/*`. This pattern would not match hidden names under `$topdir` and would therefore not find any hidden subdirectories in that directory. Kusalananda – [Kusalananda](https://unix.stackexchange.com/users/116858/kusalananda "357,784 reputation") ♦ 2021-03-06 12:41:38 +00:00 [Commented Mar 6, 2021 at 12:41](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1195156_637522) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful 1 Save this answer. Show activity on this post. Lists only directories. inclusive with spaces in names include hidden directory `-A` if needed: ``` grep '/$' <(ls -AF) ``` Possible sequels: ``` | xargs -I{} echo {} ``` ``` | while read; do echo $REPLY; done ``` But judging by the tricky question, it meant the output of directories in the `for` loop and by means of the shell: ``` for i in */ .[^.]*/; do [ -h "${i%?}" ] || echo $i done ``` [Share](https://unix.stackexchange.com/a/668227 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://unix.stackexchange.com/posts/668227/edit) Follow Follow this answer to receive notifications [edited Sep 9, 2021 at 5:28](https://unix.stackexchange.com/posts/668227/revisions "show all edits to this post") answered Sep 8, 2021 at 21:14 [![nezabudka's user avatar](https://i.sstatic.net/NLCvD.png?s=64)](https://unix.stackexchange.com/users/381427/nezabudka) [nezabudka](https://unix.stackexchange.com/users/381427/nezabudka) 2,46688 silver badges1515 bronze badges 4 - Can you explain `[ -h "${i%?}" ]` please? rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-09-09 00:06:14 +00:00 [Commented Sep 9, 2021 at 0:06](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1259129_668227) - `?` - matches any single character. It's similar `${i%/}`. Removes the trailing slash - the directory indicator. Without this, the `-h` and `-L` options in `test` do not work. nezabudka – [nezabudka](https://unix.stackexchange.com/users/381427/nezabudka "2,466 reputation") 2021-09-09 05:26:09 +00:00 [Commented Sep 9, 2021 at 5:26](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1259143_668227) - So why don't you use / then? What else would you want to remove at the end? rubo77 – [rubo77](https://unix.stackexchange.com/users/20661/rubo77 "30,745 reputation") 2021-09-14 19:48:48 +00:00 [Commented Sep 14, 2021 at 19:48](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1260651_668227) - This is just one of two equivalent options in this instance because there can only be a slash at the end. This is the first thing that came to my mind. nezabudka – [nezabudka](https://unix.stackexchange.com/users/381427/nezabudka "2,466 reputation") 2021-09-14 20:25:26 +00:00 [Commented Sep 14, 2021 at 20:25](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment1260656_668227) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful \-1 Save this answer. Show activity on this post. This lists all the directories together with the number of sub-directories in a given path: ``` for directory in */ ; do D=$(readlink -f "$directory") ; echo $D = $(find "$D" -mindepth 1 -type d | wc -l) ; done ``` [Share](https://unix.stackexchange.com/a/413157 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/413157/edit) Follow Follow this answer to receive notifications [edited Dec 26, 2017 at 19:44](https://unix.stackexchange.com/posts/413157/revisions "show all edits to this post") answered Dec 26, 2017 at 18:33 [![pabloa98's user avatar](https://www.gravatar.com/avatar/dca32d7743e08b8c4459797283317445?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/110803/pabloa98) [pabloa98](https://unix.stackexchange.com/users/110803/pabloa98) 9933 bronze badges [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful \-3 Save this answer. Show activity on this post. ``` ls -d */ | while read d do echo $d done ``` [Share](https://unix.stackexchange.com/a/218528 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/218528/edit) Follow Follow this answer to receive notifications answered Jul 27, 2015 at 1:55 [![dcat's user avatar](https://i.sstatic.net/jqUtl.png?s=64)](https://unix.stackexchange.com/users/88940/dcat) [dcat](https://unix.stackexchange.com/users/88940/dcat) 11322 bronze badges 1 - 2 `This` `is` `one` `directory` `with` `spaces` `in` `the` `name` - but gets parsed as multiple. Piskvor – [Piskvor](https://unix.stackexchange.com/users/5477/piskvor "702 reputation") 2019-03-28 11:35:28 +00:00 [Commented Mar 28, 2019 at 11:35](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment940967_218528) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| This answer is useful \-6 Save this answer. Show activity on this post. ``` ls -l | grep ^d ``` or: ``` ll | grep ^d ``` You may set it as an alias [Share](https://unix.stackexchange.com/a/391667 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://unix.stackexchange.com/posts/391667/edit) Follow Follow this answer to receive notifications [edited Sep 11, 2017 at 19:48](https://unix.stackexchange.com/posts/391667/revisions "show all edits to this post") [![Michael Mrozek's user avatar](https://www.gravatar.com/avatar/dd7e03fbbfcabd4675844173ec5390d2?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/73/michael-mrozek) [Michael Mrozek](https://unix.stackexchange.com/users/73/michael-mrozek) 96k4040 gold badges245245 silver badges236236 bronze badges answered Sep 11, 2017 at 18:46 [![user250676's user avatar](https://www.gravatar.com/avatar/06beceb37ef50b7fa850583eed50f4e9?s=64&d=identicon&r=PG)](https://unix.stackexchange.com/users/250676/user250676) [user250676](https://unix.stackexchange.com/users/250676/user250676) 1 2 - 2 Unfortunately, I don't think this answers the question, which was "I want to loop only through directories" -- which is slightly different than this `ls`\-based answer, which *lists* directories. Jeff Schaller – [Jeff Schaller](https://unix.stackexchange.com/users/117549/jeff-schaller "68,981 reputation") ♦ 2017-09-11 20:26:45 +00:00 [Commented Sep 11, 2017 at 20:26](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment698234_391667) - 4 It is never a good idea to parse the output of `ls`: [mywiki.wooledge.org/ParsingLs](https://mywiki.wooledge.org/ParsingLs) codeforester – [codeforester](https://unix.stackexchange.com/users/201820/codeforester "826 reputation") 2018-08-21 18:38:45 +00:00 [Commented Aug 21, 2018 at 18:38](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash#comment844492_391667) [Add a comment](https://unix.stackexchange.com/questions/86722/how-do-i-loop-through-only-directories-in-bash "Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”.") \| ## You must [log in](https://unix.stackexchange.com/users/login?ssrc=question_page&returnurl=https%3A%2F%2Funix.stackexchange.com%2Fquestions%2F86722) to answer this question. **[Protected question](https://unix.stackexchange.com/help/privileges/protect-questions)**. To answer this question, you need to have at least 10 reputation on this site (not counting the [association bonus](https://meta.stackexchange.com/questions/141648/what-is-the-association-bonus-and-how-does-it-work)). The reputation requirement helps protect this question from spam and non-answer activity. Start asking to get answers Find the answer to your question by asking. [Ask question](https://unix.stackexchange.com/questions/ask) Explore related questions - [bash](https://unix.stackexchange.com/questions/tagged/bash "show questions tagged 'bash'") - [files](https://unix.stackexchange.com/questions/tagged/files "show questions tagged 'files'") - [directory](https://unix.stackexchange.com/questions/tagged/directory "show questions tagged 'directory'") See similar questions with these tags. - The Overflow Blog - [Building brains for bulldozers](https://stackoverflow.blog/2026/03/06/building-brains-for-bulldozers/?cb=1) - Featured on Meta - [Logo updates to Stack Overflow's visual identity](https://meta.stackexchange.com/questions/417394/logo-updates-to-stack-overflows-visual-identity?cb=1) #### Linked [0](https://unix.stackexchange.com/questions/591642/what-is-the-proper-way-to-loop-through-each-directory-in-a-for-loop?lq=1 "Question score (upvotes - downvotes)") [What is the proper way to loop through each directory in a for loop?](https://unix.stackexchange.com/questions/591642/what-is-the-proper-way-to-loop-through-each-directory-in-a-for-loop?noredirect=1&lq=1) [220](https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice?lq=1 "Question score (upvotes - downvotes)") [Why is looping over find's output bad practice?](https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice?noredirect=1&lq=1) [202](https://unix.stackexchange.com/questions/389705/understanding-the-exec-option-of-find?lq=1 "Question score (upvotes - downvotes)") [Understanding the -exec option of \`find\`](https://unix.stackexchange.com/questions/389705/understanding-the-exec-option-of-find?noredirect=1&lq=1) [8](https://unix.stackexchange.com/questions/85457/how-to-circumvent-too-many-open-files-in-debian?lq=1 "Question score (upvotes - downvotes)") [How to circumvent "Too many open files" in debian](https://unix.stackexchange.com/questions/85457/how-to-circumvent-too-many-open-files-in-debian?noredirect=1&lq=1) [4](https://unix.stackexchange.com/questions/96913/test-for-link-with-trailing-slash?lq=1 "Question score (upvotes - downvotes)") [Test for link with trailing slash?](https://unix.stackexchange.com/questions/96913/test-for-link-with-trailing-slash?noredirect=1&lq=1) [1](https://unix.stackexchange.com/questions/362037/how-can-i-compress-files-with-the-output-name-same-as-parent-folder?lq=1 "Question score (upvotes - downvotes)") [How can I compress files with the output name same as parent folder?](https://unix.stackexchange.com/questions/362037/how-can-i-compress-files-with-the-output-name-same-as-parent-folder?noredirect=1&lq=1) [1](https://unix.stackexchange.com/questions/729011/rename-directories-add-dashes-after-fourth-and-sixth-characters?lq=1 "Question score (upvotes - downvotes)") [Rename directories add dashes after fourth and sixth characters](https://unix.stackexchange.com/questions/729011/rename-directories-add-dashes-after-fourth-and-sixth-characters?noredirect=1&lq=1) [1](https://unix.stackexchange.com/questions/707930/bash-script-copy-from-a-folder-to-another-within-a-directory-and-loop-the-proce?lq=1 "Question score (upvotes - downvotes)") [bash script: copy from a folder to another within a directory and loop the process over multiple directories](https://unix.stackexchange.com/questions/707930/bash-script-copy-from-a-folder-to-another-within-a-directory-and-loop-the-proce?noredirect=1&lq=1) #### Related [5](https://unix.stackexchange.com/questions/125270/remove-linux-directories-containing-only-old-files?rq=1 "Question score (upvotes - downvotes)") [Remove Linux directories containing ONLY old files](https://unix.stackexchange.com/questions/125270/remove-linux-directories-containing-only-old-files?rq=1) [8](https://unix.stackexchange.com/questions/154525/linux-command-line-move-all-files-and-directories-in-directory-except-some-fil?rq=1 "Question score (upvotes - downvotes)") [Linux command line. Move all files and directories in directory, except some files and directories](https://unix.stackexchange.com/questions/154525/linux-command-line-move-all-files-and-directories-in-directory-except-some-fil?rq=1) [1](https://unix.stackexchange.com/questions/187854/loop-through-multiple-folders-and-perform-commands-then-write-to-file?rq=1 "Question score (upvotes - downvotes)") [loop through multiple folders and perform commands then write to file](https://unix.stackexchange.com/questions/187854/loop-through-multiple-folders-and-perform-commands-then-write-to-file?rq=1) [17](https://unix.stackexchange.com/questions/351210/loop-through-files-excluding-directories?rq=1 "Question score (upvotes - downvotes)") [Loop through files excluding directories](https://unix.stackexchange.com/questions/351210/loop-through-files-excluding-directories?rq=1) [0](https://unix.stackexchange.com/questions/353540/loop-through-specific-set-of-directories?rq=1 "Question score (upvotes - downvotes)") [Loop through specific set of directories](https://unix.stackexchange.com/questions/353540/loop-through-specific-set-of-directories?rq=1) [0](https://unix.stackexchange.com/questions/500157/loop-through-many-folders-and-do-calculations-with-files-with-similar-pattern-in?rq=1 "Question score (upvotes - downvotes)") [Loop through many folders and do calculations with files with similar pattern in bash](https://unix.stackexchange.com/questions/500157/loop-through-many-folders-and-do-calculations-with-files-with-similar-pattern-in?rq=1) [2](https://unix.stackexchange.com/questions/589475/how-can-i-exclude-and-when-listing-only-hidden-items?rq=1 "Question score (upvotes - downvotes)") [How can I exclude . and .. when listing only hidden items?](https://unix.stackexchange.com/questions/589475/how-can-i-exclude-and-when-listing-only-hidden-items?rq=1) [3](https://unix.stackexchange.com/questions/676561/tarring-gzipping-only-hidden-directories-or-files-directories?rq=1 "Question score (upvotes - downvotes)") [Tarring-gzipping only hidden directories (or files + directories)](https://unix.stackexchange.com/questions/676561/tarring-gzipping-only-hidden-directories-or-files-directories?rq=1) #### [Hot Network Questions](https://stackexchange.com/questions?tab=hot) - [Fail to replicate a sloped node with label node](https://tex.stackexchange.com/questions/760657/fail-to-replicate-a-sloped-node-with-label-node) - [A very rickety series of spurious connections](https://puzzling.stackexchange.com/questions/137360/a-very-rickety-series-of-spurious-connections) - [Possible configurations of the four self-intersection points of a closed plane curve](https://mathematica.stackexchange.com/questions/318965/possible-configurations-of-the-four-self-intersection-points-of-a-closed-plane-c) - [Construction of a monoid that can't be embedded in a group.](https://math.stackexchange.com/questions/5128142/construction-of-a-monoid-that-cant-be-embedded-in-a-group) - [Why does Exodus 12 require the Passover lamb to be “kept” for four days (Exodus 12:3–6)?](https://hermeneutics.stackexchange.com/questions/115228/why-does-exodus-12-require-the-passover-lamb-to-be-kept-for-four-days-exodus) - [Is this an incorrect definition of the automorphism group of a graph?](https://math.stackexchange.com/questions/5128096/is-this-an-incorrect-definition-of-the-automorphism-group-of-a-graph) - [At the very end of "Diary of a Chambermaid," what does Joseph shout?](https://movies.stackexchange.com/questions/131573/at-the-very-end-of-diary-of-a-chambermaid-what-does-joseph-shout) - [Should I cross my fingers while playing staccato scales on the piano?](https://music.stackexchange.com/questions/143337/should-i-cross-my-fingers-while-playing-staccato-scales-on-the-piano) - [Investigating an odd name for a network operator](https://android.stackexchange.com/questions/265142/investigating-an-odd-name-for-a-network-operator) - [Approximation of multivariant Lipschitz functions by piecewise linear functions](https://mathoverflow.net/questions/508932/approximation-of-multivariant-lipschitz-functions-by-piecewise-linear-functions) - [Why drive 650nm 5mW laser with a constant current source?](https://electronics.stackexchange.com/questions/766689/why-drive-650nm-5mw-laser-with-a-constant-current-source) - [K-theory and adic completion](https://mathoverflow.net/questions/508937/k-theory-and-adic-completion) - [Why does searching an email address via grep on this site not give any results?](https://superuser.com/questions/1935663/why-does-searching-an-email-address-via-grep-on-this-site-not-give-any-results) - [Evolution Microsoft 365 calendar error: 'Could not find a property named contentBytes on type microsoft.graph.attachment' on Ubuntu 24.04](https://askubuntu.com/questions/1564699/evolution-microsoft-365-calendar-error-could-not-find-a-property-named-content) - [Lk 10:8-11: Why weren't the disciples told to preach repentance on their first missionary itinerary?](https://hermeneutics.stackexchange.com/questions/115230/lk-108-11-why-werent-the-disciples-told-to-preach-repentance-on-their-first-m) - [How does hunting animals work exactly?](https://gaming.stackexchange.com/questions/418120/how-does-hunting-animals-work-exactly) - [Network Block Device: nbd-server](https://serverfault.com/questions/1198413/network-block-device-nbd-server) - [How to perform replacement without evaluating an expression before passing forward?](https://mathematica.stackexchange.com/questions/318974/how-to-perform-replacement-without-evaluating-an-expression-before-passing-forwa) - [Were Paul and Leto II the only ones who could have become God Emperor?](https://scifi.stackexchange.com/questions/303609/were-paul-and-leto-ii-the-only-ones-who-could-have-become-god-emperor) - [What's the intended use case for using shred utility on the standard output?](https://unix.stackexchange.com/questions/804902/whats-the-intended-use-case-for-using-shred-utility-on-the-standard-output) - [Why does friction suddenly change when something like a car turns? This makes no sense to me](https://physics.stackexchange.com/questions/869968/why-does-friction-suddenly-change-when-something-like-a-car-turns-this-makes-no) - [Go board game in C++ using SFML](https://codereview.stackexchange.com/questions/301567/go-board-game-in-c-using-sfml) - [In Massachusetts, why do laws that prohibit nudity require a witness be offended, alarmed, or shocked?](https://law.stackexchange.com/questions/114360/in-massachusetts-why-do-laws-that-prohibit-nudity-require-a-witness-be-offended) - [Do you bleed brakes after experiencing fade?](https://bicycles.stackexchange.com/questions/100067/do-you-bleed-brakes-after-experiencing-fade) [Question feed](https://unix.stackexchange.com/feeds/question/86722 "Feed of this question and its answers") # Subscribe to RSS Question feed To subscribe to this RSS feed, copy and paste this URL into your RSS reader. ![](https://unix.stackexchange.com/posts/86722/ivc/e014?prg=89dd7902-4415-4fee-b0a4-5773c15113ea) lang-bash # Why are you flagging this comment? It contains harassment, bigotry or abuse. This comment attacks a person or group. Learn more in our [Abusive behavior policy](https://unix.stackexchange.com/conduct/abusive-behavior). It's unfriendly or unkind. This comment is rude or condescending. Learn more in our [Code of Conduct](https://unix.stackexchange.com/conduct/abusive-behavior). Not needed. This comment is not relevant to the post. ``` ``` Enter at least 6 characters Something else. A problem not listed above. Try to be as specific as possible. ``` ``` Enter at least 6 characters Flag comment Cancel You have 0 flags left today # ![Illustration of upvote icon after it is clicked](https://unix.stackexchange.com/Content/Img/modal/img-upvote.png?v=fce73bd9724d) # Hang on, you can't upvote just yet. You'll need to complete a few actions and gain 15 reputation points before being able to upvote. **Upvoting** indicates when questions and answers are useful. [What's reputation and how do I get it?](https://stackoverflow.com/help/whats-reputation) Instead, you can save this post to reference later. Save this post for later Not now ##### [Unix & Linux](https://unix.stackexchange.com/) - [Tour](https://unix.stackexchange.com/tour) - [Help](https://unix.stackexchange.com/help) - [Chat](https://chat.stackexchange.com/?tab=site&host=unix.stackexchange.com) - [Contact](https://unix.stackexchange.com/contact) - [Feedback](https://unix.meta.stackexchange.com/) ##### [Company](https://stackoverflow.co/) - [Stack Overflow](https://stackoverflow.com/) - [Stack Internal](https://stackoverflow.co/internal/) - [Stack Data Licensing](https://stackoverflow.co/data-licensing/) - [Stack Ads](https://stackoverflow.co/advertising/) - [About](https://stackoverflow.co/) - [Press](https://stackoverflow.co/company/press/) - [Legal](https://stackoverflow.com/legal) - [Privacy Policy](https://stackoverflow.com/legal/privacy-policy) - [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public) - Cookie Settings - [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy) ##### [Stack Exchange Network](https://stackexchange.com/) - [Technology](https://stackexchange.com/sites#technology) - [Culture & recreation](https://stackexchange.com/sites#culturerecreation) - [Life & arts](https://stackexchange.com/sites#lifearts) - [Science](https://stackexchange.com/sites#science) - [Professional](https://stackexchange.com/sites#professional) - [Business](https://stackexchange.com/sites#business) - [API](https://api.stackexchange.com/) - [Data](https://data.stackexchange.com/) - [Blog](https://stackoverflow.blog/?blb=1) - [Facebook](https://www.facebook.com/officialstackoverflow/) - [Twitter](https://twitter.com/stackoverflow) - [LinkedIn](https://linkedin.com/company/stack-overflow) - [Instagram](https://www.instagram.com/thestackoverflow) Site design / logo © 2026 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2026.3.10.40793 Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group. This site is not affiliated with Linus Torvalds or The Open Group in any way.
Readable Markdown
This answer is assuming that *all* that needs to be done is to find the sub-directories of some top-level directory. For an answer specific to `bash` (and to some degree, the `zsh` shell), see the second part of [rubo77's wiki answer](https://unix.stackexchange.com/a/96904/116858), where `dotglob` and `nullglob` is being used to correctly loop over the directories (or symbolic links to directories) in a single directory. For a portable solution that does not depend on `bash` for doing the actual selection of files, you may use `find` to loop over all directories in some top-level directory like so: ``` topdir=. find "$topdir" ! -path "$topdir" -prune -type d -exec sh -c ' for dirpath do # user code goes here, using "$dirpath" printf "\"%s\" is a directory\n" "$dirpath" done' sh {} + ``` The above code assumes that the top directory that we're interested in is the current directory (`.`). Set `topdir` to some other pathname to use it on another directory. The `find` utility is asked to ignore pathnames that are identical to the starting search path with `! -path "$topdir"`, and then to prune (not enter) any other pathnames found. This limits the search to only the directory referenced by `$topdir`. Pathnames that are directories (`-type d`) are collected and a `sh -c` script is executed with batches of these as arguments. The `sh -c` script is the code that we'd like to execute on all the directories, so it iterates over its given arguments and does whatever it needs to do with each of them. If you need to do something that requires `bash`, you would obviously use `bash -c` instead. The `sh -c` script could be separated out into its own script like so: ``` #!/bin/sh for dirpath do # user code goes here, using "$dirpath" printf '"%s" is a directory\n' "$dirpath" done ``` ... which would be called from `find` like so: ``` find "$topdir" ! -path "$topdir" -prune -type d -exec ./myscript.sh {} + ``` See also: - [Understanding the -exec option of \`find\`](https://unix.stackexchange.com/questions/389705)
ML Classification
ML Categories
/Computers_and_Electronics
99.0%
/Computers_and_Electronics/Software
62.4%
/Computers_and_Electronics/Software/Software_Utilities
30.8%
/Internet_and_Telecom
15.9%
/Internet_and_Telecom/Web_Services
13.4%
/Internet_and_Telecom/Web_Services/Web_Design_and_Development
11.2%
Raw JSON
{
    "/Computers_and_Electronics": 990,
    "/Computers_and_Electronics/Software": 624,
    "/Computers_and_Electronics/Software/Software_Utilities": 308,
    "/Internet_and_Telecom": 159,
    "/Internet_and_Telecom/Web_Services": 134,
    "/Internet_and_Telecom/Web_Services/Web_Design_and_Development": 112
}
ML Page Types
/Article
92.6%
/Article/FAQ
61.9%
Raw JSON
{
    "/Article": 926,
    "/Article/FAQ": 619
}
ML Intent Types
Informational
99.9%
Raw JSON
{
    "Informational": 999
}
Content Metadata
Languageen
Authornull
Publish Time2013-08-14 15:43:37 (12 years ago)
Original Publish Time2013-08-14 15:43:37 (12 years ago)
RepublishedNo
Word Count (Total)4,866
Word Count (Content)352
Links
External Links45
Internal Links201
Technical SEO
Meta NofollowNo
Meta NoarchiveNo
JS RenderedYes
Redirect Targetnull
Performance
Download Time (ms)133
TTFB (ms)105
Download Size (bytes)59,077
Shard18 (laksa)
Root Hash8045678284012640218
Unparsed URLcom,stackexchange!unix,/questions/86722/how-do-i-loop-through-only-directories-in-bash s443