I have the following instructions:

  1. Find all files in the directory /x/y/z with the extension .jpg.
  2. Write a list of matching filenames, one per line, to the file /x/y/file1.txt.
  3. Ensure that you specify the absolute path to each file.

Can you assist with understanding this instruction? I initially thought of using the following command:

find /x/y/z -name '*.jpg' -exec basename '{}' >> /x/y/file1.txt \;

However, given the last instruction (...absolute path), I consider:

find /x/y/z -name '*.jpg' -exec pathname '{}' >> /x/y/file1.txt \;

Which is the correct response (command) to the question/instruction?

  • It seems that requirements #2 and #3 are either in opposition, or the word filenames should be taken to mean pathnames. In this case ls /x/y/z/*.jpg >/x/y/file1.txt would suffice, but it's not clear to me how to satisfy both #2 and #3 if filenames is taken as its usual meaning of a filename component without path Aug 12, 2021 at 18:38

1 Answer 1


In this answer I'm assuming that the second point of your instructions actually means "pathnames" rather than "filenames". The third point does not make sense otherwise.

The find utility will, by default, output the full path to the found files, relative to the top-level search path.

In the command

find /x/y/z -name '*.jpg' -print

... find will print out pathnames like /x/y/z/foo/bar/baz.jpg. If the top-level search path is the absolute pathname to some directory, then the output would automatically be absolute pathnames to found files.

On the other hand, if you're using

find x/y/z -name '*.jpg' -print

(note the lack of / at the start of x/y/z), then you will obviously get relative pathnames outputted.

You may turn these into absolute pathnames using the utility realpath on Linux:

find x/y/z -name '*.jpg' -exec realpath {} +

This calls realpath with batches of found pathnames.

On non-Linux systems, the same realpath utility may be installed if one installs GNU coreutils (but it may then be called grealpath).

See also man realpath (or man grealpath).

Re-reading your instructions, there is nothing in them that implies that you should be using find. You don't need to use find if you're only concerned with the names in a single directory.

The exercise could just as well be solved by

printf '%s\n' /x/y/z/*.jpg >/x/y/file1.txt

This lists all names ending with .jpg in the directory /x/y/z. If you don't have the absolute path to that directory at hand, then use

realpath x/y/z/*.jpg >/x/y/file1.txt
  • Thanks @Kusalananda and roamima. This is very helpful. I will work with these insights.
    – WildGTX
    Aug 12, 2021 at 19:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .