7

I know that * references all files excluding hidden files, how to reference all files including hidden files whose names begin with a . in bash?

3
  • 1
    (Sidenote warning: all directory entries, including those starting with ., would in particular include the "current directory" entry . and the "parent directory" entry ... Just so you're warned.) Nov 27, 2015 at 5:27
  • 1
    @UlrichSchwarz yes, .* references all hidden files including "current directory" and "parent directory"
    – tmpbin
    Nov 27, 2015 at 6:27
  • 1
    Outside the bash-specific scope of the question, but zsh's globbing has handy type qualifiers, so that you can use e.g. ls .*(.) which will match only regular files (.), not symlinks (@) or directories (/) or the like. Especially helpful when doing e.g. grep something **/*(.), which will grep inside all regular files at any depth below the current directory, without throwing errors for trying to grep inside the directory entries themselves.
    – FeRD
    Nov 27, 2015 at 8:01

4 Answers 4

11

bash has a dotglob option that makes * include names starting with .:

echo *           # let's see some files
shopt -s dotglob # enable dotglob
echo *           # now with dotfiles
shopt -u dotglob # disable dotglob again
echo *           # back to the beginning
0
3

Use the shell option dotglob:

shopt  -s dotglob
echo *

For more information, see the bash manual: http://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html

1

You could use brace expansion and write {,.}* which expands to * .* and thus includes both normal and hidden files.

1
  • Thanks for your answer, but this has a problem. When used in a recursive command, it also affects the previous directory (..) and all subdirectories in the previous directory! This command should only affect files and directories contained in the CURRENT directory (and the ones contained in each recursively read directory), but it should never go up in the hierarchy and affect neightbouring directories.
    – OMA
    Oct 15, 2019 at 12:30
0
files=($(ls -a))
for file in "${files[@]}"; do
  echo "${file}"
done
3
  • 2
    fails on unusual filenames with spaces or tabs or newlines etc.
    – cas
    Nov 27, 2015 at 5:45
  • The cleaned-up version of this would be to use IFS="^v^j" (actually type Ctrl-v and Ctrl-j) to set the input separator to newline, then ls -A -1 to list the matches one-per-line. (ls -A explicitly excludes . and .. from the -a listing, it's good to get in the habit of using because it's almost always what you really want.) Of course, none of that would be necessary if ls supported null-delimited output lists, then you could just pipe its output to xargs -0. Never understood why there's no support for an ls -0 parameter.
    – FeRD
    Nov 27, 2015 at 8:09
  • What are you on windows?
    – jas-
    Nov 27, 2015 at 16:17

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