user15596049
user15596049

Reputation:

How can I list only sub-directories using "ls" with absolute(full) path or achieving it wihout "ls"?

I know that using ls -d */ list only sub-directories in the current directory but I want to list with it absolute paths.

Can I achieve it?

I know just listing the any files of the current directories with absolute paths are done by typing ls -d $PWD/*

For instance as we are in /home/boston/ and run ls -d */ , we get the following sub-directories with relative paths.

Desktop/  Documents/  Downloads/  kl/  Music/  Pictures/  Public/  Templates/  Videos/

Upvotes: 0

Views: 2130

Answers (4)

user15596049
user15596049

Reputation:

We can achieve this with ls by just typing

ls -d $PWD*/*/

or

ls -d $PWD/*/

Upvotes: 1

Kaz
Kaz

Reputation: 58578

Unless this is a "how to do this with ls" puzzle, so that non-ls solutions are disqualified, the normal way to do this in daily scripting would be to use the find utility:

find "$(pwd)" -type d

Now, that will include the current directory itself in the listing. If we have GNU find, we can use

find "$(pwd)" -mindepth 1 -type d

to prune that away, or else filter it out of the output in other ways.

GNU find's mindepth and maxdepth can restrict to just the direct subdirectories of the current directory:

find "$(pwd)" -mindepth 1 -maxdepth 1 -type d

Also, note I'm using the pwd utility, not the PWD variable. The utility is more reliable because it inquires the operating system kernel via the getcwd library function, whereas PWD is just a variable maintained by the shell whose value is only correct if it has been correctly maintained.

$ PWD=42
$ echo $PWD
42

PWD is useful in shell script fragments for customizing the personal environment, not anything that should be halfway robust under all imaginable circumstances.

pwd has useful options; eg with pwd -P you can have the path canonicalized, so it is free of symbolic links.

Upvotes: 3

Gordon Davisson
Gordon Davisson

Reputation: 125798

If you just want a list of filenames, you don't actually need ls here; the correct glob (wildcard) expression will give a list of paths, you just need something to print them:

echo "$PWD"/*/    # Prints them with spaces between
printf '%s\n' "$PWD"/*/    # Prints each one on a separate line

The main limitation with these is that if there aren't any subdirectories, they'll go ahead and print the unexpanded wildcard (e.g. "/home/boston/*/"). ls will actually check each one before printing it, and give you an error like "No such file or directory" if there's no match.

Upvotes: 0

Amirshk
Amirshk

Reputation: 8258

This should work:

ls -d $PWD*/

Upvotes: 1

Related Questions