Listing only directories using ls in bash: An exam

2019-01-05 06:22发布

This command lists directories in the current path: ls -d */

What exactly does the pattern */ do?

And how can we give the absolute path in the above command (e.g. ls -d /home/alice/Documents) for listing only directories in that path?

25条回答
闹够了就滚
2楼-- · 2019-01-05 07:06

Test whether the item is a directory with test -d:

for i in $(ls); do test -d $i && echo $i ; done
查看更多
Root(大扎)
3楼-- · 2019-01-05 07:07

FYI, if you want to print all the files in multi-line, you can do a ls -1 which will print each file in a separate line. file1 file2 file3

查看更多
唯我独甜
4楼-- · 2019-01-05 07:09

I use:

ls -d */ | cut -f1 -d'/'

This creates a single column with no trailing slash - useful in scripts.

My two cents.

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-05 07:09

I partially solved with :

cd "/path/to/pricipal/folder"

for i in $(ls -d .*/); do sudo ln -s "$PWD"/${i%%/} /home/inukaze/${i%%/}; done

ln: «/home/inukaze/./.»: can't overwrite a directory
ln: «/home/inukaze/../..»: can't overwrite a directory
ln: accesing to «/home/inukaze/.config»: too much symbolics links levels
ln: accesing to «/home/inukaze/.disruptive»: too much symbolics links levels
ln: accesing to «/home/inukaze/innovations»: too much symbolics links levels
ln: accesing to «/home/inukaze/sarl»: too much symbolics links levels
ln: accesing to «/home/inukaze/.e_old»: too much symbolics links levels
ln: accesing to «/home/inukaze/.gnome2_private»: too much symbolics links levels
ln: accesing to «/home/inukaze/.gvfs»: too much symbolics links levels
ln: accesing to «/home/inukaze/.kde»: too much symbolics links levels
ln: accesing to «/home/inukaze/.local»: too much symbolics links levels
ln: accesing to «/home/inukaze/.xVideoServiceThief»: too much symbolics links levels

Well , this reduce to me , the mayor part :)

查看更多
走好不送
6楼-- · 2019-01-05 07:12

In case you're wondering why output from 'ls -d */' gives you two trailing slashes, like:

[prompt]$ ls -d */    
app//  cgi-bin//  lib//        pub//

it's probably because somewhere your shell or session config files alias the ls command to a version of ls that includes the -F flag. That flag appends a character to each output name (that's not a plain file) indicating the kind of thing it is. So one slash is the from matching the pattern '*/', and the other slash is the appended type indicator.

To get rid of this issue, you could of course define a different alias for ls. However, to temporarily not invoke the alias, you can prepend the command with backslash:

\ls -d */

查看更多
Viruses.
7楼-- · 2019-01-05 07:13

If hidden directory is not needed to be listed, I offer:

ls -l | grep "^d" | awk -F" " '{print $9}'  

And if hidden directories is needed to be listed, use:

ls -Al | grep "^d" | awk -F" " '{print $9}'

OR

find -maxdepth 1 -type d | awk -F"./" '{print $2}'
查看更多
登录 后发表回答