Print absolute paths of files and directories in the current directory

(shopt -s dotglob; ls -1d "$PWD"/*)

March 28, 2019Julien_Tremblay_McLellan

Explanation

ls prints the list of files:

  • The -1 flag makes it print one file per line, even if multiple would fit in the terminal.
  • The -d flag makes it not list the content of directories. For example ls /tmp would normally print the files inside /tmp, but ls -d /tmp will print just /tmp itself.
  • "$PWD" is a builtin variable of Bash, it always contains the absolute path of the current shell.
  • The shell expands "$PWD"/* to the absolute paths of the files and directories in the current directory.

shopt -s dotglob changes the behavior of the glob operator *: normally * does not match hidden files (whose name starts with .), so for example if there is a file named .bashrc in the current directory, ls * would not show it. shopt -s dotglob makes * also match such files. Note that even with this option the special filenames . and .. will not be matched. And that's precisely what we want here: we want to see the absolute paths of all files and directories in the current directory, the special filenames . and .. would be noise.

We wrapped the entire command inside (...), which makes it a sub-shell. This means that changes to the shell environment, such as the effect of shopt commands will not be visible outside the sub-shell. We did this because we only want to use shopt -s dotglob for this single operation, we want to keep the default behavior in the current shell.