Linux – ls with directory path shows files, but ls with file pattern does not


Why is this happening?

$ sudo ls /var/lib/postgresql/9.4/pg_log/
postgresql-2015-03-23_134626.log  postgresql-2015-03-25_000000.log  postgresql-2015-03-25_095920.log
postgresql-2015-03-24_000000.log  postgresql-2015-03-25_095626.log
$ sudo ls /var/lib/postgresql/9.4/pg_log/*
ls: cannot access /var/lib/postgresql/9.4/pg_log/*: No such file or directory

ls /path/to/dir/ shows files, but ls /path/to/dir/* says no files found.

Why is this?

Best Answer

The wildcard is expanded by the shell before sudo is run. The current user can't access the files, so the string is passed literally to sudo and later ls. ls doesn't expand wildcards (it's the shell's duty), so it can't find the file named *.

Protect the wildcard by quoting and call a root shell to expand it:

sudo sh -c 'ls /var/lib/postgresql/9.4/pg_log/*'
Related Question