0

I'm trying to get the names of the folders inside another folder. I was trying to use the bellow code but the problem is that it return the full address of the folder instead of just the folder name

for folder in /[my folder]/*; do cat $folder;  done

With this I get /[my folder]/subfolder1, what I expected was just the subfolder1.

Thank you

6

cat is a program that simply takes its input stream, or a file, and prints it to standard output. You cannot cat a directory, that doesn't make sense. If you just want to see the names of all first level subdirectories of a given directory, you can use echo which simply prints what you give it:

$ for dir in foo/*/; do echo "$dir"; done
foo/dir1/
foo/dir2/
foo/dir3/
foo/dir4/

You don't even need a loop:

$ echo foo/*/
foo/dir1/ foo/dir2/ foo/dir3/ foo/dir4 

To get only the directory names, without the path:

$ for dir in foo/*/; do basename "$dir"; done
dir1
dir2
dir3
dir4

Alternatively, you can cd to the path:

$ cd foo
$ echo */
dir1/ dir2/ dir3/ dir4/

Or cd in a subshell so you stay where you were originally when the command finishes:

$ ( cd foo && echo */ )
dir1/ dir2/ dir3/ dir4/

Or, to get them on separate lines and also to ensure that this will work even on weird directory names (e.g. a name that contains a newline):

    $ ( cd foo && printf -- '%s\n' */ ) 
    dir1/
    dir2/
    dir3/
    dir4/
    

Finally, if your directory names can contain newlines or other strangeness, use:

| improve this answer | |
  • This was perfect, thank you very much! – Filipe Lemos Oct 17 at 18:07
  • basename -- "$dir", with double dash, to avoid pitfalls. – rexkogitans Oct 17 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.