How to display only hidden files in directory using ls command in Bash

风格不统一 提交于 2019-12-11 06:04:02

问题


I am trying to display the hidden files from a directory using the ls command alone, except for . and ...

ls -lAd .*

But the command returns . and .. directory names also in the output . What's wrong in this command even though I mentioned "A" option with ls .


回答1:


You could use GLOBIGNORE internal variable.

$ GLOBIGNORE=.:..
$ ls -ld .*



回答2:


This is here for reference but the answer is given by @anishsane below.

Your glob is wrong:

.*

will be expanded to ., and ... You can either change the glob to something like:

.??*

but this will not match hidden files like: .a, .b. Or .[^.]* but that will not match files like ..a, ..b, combining both might be an option:

ls -lAd .[^.]*  ..?*

But that will most likely yeild: ls: error: ..?* no such file or directory. Enabling nullglob will prevent this:

shopt -s nullglob
ls -lAd .[^.]*  ..?*

This will however expand to ls -lAd if no hidden files are in the directory, which will show current working directory (.)

Alternative you can pipe the output from ls to awk, but that will most likely get rid of the colors:

ls -lA | awk '$9 ~ /^\./'

Also consider reading: Why you shouldn't parse the output of ls(1)



来源:https://stackoverflow.com/questions/37850169/how-to-display-only-hidden-files-in-directory-using-ls-command-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!