I am writing a shell script that takes file paths as input.
For this reason, I need to generate recursive file listings with full paths. For example, the file bar
has the path:
/home/ken/foo/bar
but, as far as I can see, both ls
and find
only give relative path listings:
./foo/bar (from the folder ken)
It seems like an obvious requirement, but I can't see anything in the find
or ls
man pages.
How can I generate a list of files in the shell including their absolute paths?
To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.
The easiest way to create a new file in Linux is by using the touch command. The ls command lists the contents of the current directory. Since no other directory was specified, the touch command created the file in the current directory.
The answer is the pwd command, which stands for print working directory. The word print in print working directory means “print to the screen,” not “send to printer.” The pwd command displays the full, absolute path of the current, or working, directory.
If you give find
an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:
find "$(pwd)" -name .htaccess
or if your shell expands $PWD
to the current directory:
find "$PWD" -name .htaccess
find
simply prepends the path it was given to a relative path to the file from that path.
Greg Hewgill also suggested using pwd -P
if you want to resolve symlinks in your current directory.
readlink -f filename
gives the full absolute path. but if the file is a symlink, u'll get the final resolved name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With