Bash – Why doesn’t the command “ ls “*” ” show anything
bashlswildcards
ls "*"
This shows nothing in my directory. Why?
Isn't * a wildcard that will show everything?
Best Answer
When it's in double quotes the * doesn't get treated as a glob, and so doesn't get expanded. So you're asking ls to list a file named *, which probably doesn't exist.
To see all the files, you could run ls without any arguments as it's default behavior is to show you all the files in the current directory. If you wanted to pass all the files as arguments to ls for some reason, just remove the quotes so you run
ls *
but that's really similar to
ls
except that if you have a lot of files * might expand to pass too many arguments to ls, and also ls * will show the contents of directories while ls by itself will just show that the directories are in the current directory without descending into them.
The shell takes your input and expands the .* part before passing it to ls, so effectively you're doing:
$ ls .bash_history .bash_profile .bashrc .coin_history .emacs ...
So it lists each entry. When it sees a directory entry, it lists the contents of that directory, just as you would expect ls to do. To see only the files/directories in your working directory, use the -d option to ls:
$ ls -d .*
The -d option tells ls to "list directories themselves, not their contents" (taken from the lsman page).
I figured it out! Looking more closely at the documentation for shopt, there's an option called dotglob that can be used to include filenames that begin with a dot!
I added shopt -s dotglob to the beginning of my script and it works now. The output now lists every hidden file and directory (except ./ and ../).
My script now looks like this:
#!/bin/bash
shopt -s extglob
shopt -s dotglob
for i in "$(pwd)"/*; do
echo "$i"
done
Best Answer
When it's in double quotes the
*
doesn't get treated as a glob, and so doesn't get expanded. So you're askingls
to list a file named*
, which probably doesn't exist.To see all the files, you could run
ls
without any arguments as it's default behavior is to show you all the files in the current directory. If you wanted to pass all the files as arguments tols
for some reason, just remove the quotes so you runbut that's really similar to
except that if you have a lot of files
*
might expand to pass too many arguments tols
, and alsols *
will show the contents of directories whilels
by itself will just show that the directories are in the current directory without descending into them.