0

In a directory, "Global" I have muliple files and directories. The file names are not consitant. They might or might not have extension, there's upper and lower case letters along with numbers in the filename.

abc.txt
aBCd
abcd124fg
123ABCD.csv

I would like to check, If there are any files in the "Global" directory then just list all the file names but not the directories. Is this possible since I don't know what the file name will be?

user1736786
  • 139
  • 1
  • 4
  • 11
  • 1
    `for i in Global/*; do [ -f "$i" ] && echo "$i"; done` or, `find Global -maxdepth 1 -type f` To ignore empty files in the first example, change `-f` to `-s`. – David C. Rankin Dec 05 '20 at 02:40
  • 1
    Does this answer your question? [How to list only files and not directories of a directory Bash?](https://stackoverflow.com/questions/10574794/how-to-list-only-files-and-not-directories-of-a-directory-bash) – Stephen C Dec 05 '20 at 03:03
  • The command to works great on how to list only the files but If I want to check if the file exist, how do I go about doing this. So something like this: `if [ -f $FILE ]; then for i in Global/*; do [ -f "$i" ] && echo "$i"; done else echo "No Files to see here" fi` But since I don't know what the filename is call or even if it has an extension. How do I do check if there's any files in the Global directory? `if [ -f $FILE ]; then` So what would $FILE be?? – user1736786 Dec 05 '20 at 17:37

1 Answers1

0

You may want to use the find command in bash and let it gather all that's in Global:

find ./Global -type f -name '*' -printf '%f\n'

That will give you all the existing files/names inside Global and subdirectories without anything else. The "%f" will give you the filenames only without the path.

This is basically all you need to loop through or if-state whatever you want with this list - it can be saved in an array or in a textfile you can then use for anything you want, like your task, which would be:

if [[ $(find ./Global -type f -name '*' -printf '%f\n') ]]; then
    echo "Files found in Global"
else
    echo "No files in Global"
fi