Reputation: 7228
I need to get a file name from a directory for the file to be processed on my UNIX system. There will be only one file in the directory and its name changes dynamically (by an un-named outside methodology).
Please let me know how this can be done.
Upvotes: 0
Views: 20170
Reputation: 755026
If there's only one file name that doesn't begin with a .
, then:
filename="$(ls $directory)"
This captures the output of ls
. Because of the 'one file' limitation, it is safe even if the name contains newlines, spaces, tabs, or whatever. With multiple files, parsing the output of ls
is problematic.
If you want the pathname, rather than just the filename, you can use:
filename=$directory/*
Again, this is only safe because of the 'one file' limitation. It is not possible to use this to distinguish between 'there is one file in the directory and its name is *
' and the error case 'there are no files in the directory at all'. With ls
, if the string is empty, there is no file.
If the file name might start with .
, then life is a lot harder; you probably use:
filename=$(cd $directory; basename "$(find . -type f)")
Once more, this is safe only because of the 'one file' limit. If there might be multiple files, you need to use other techniques altogether.
Upvotes: 4