Globbing only for files in bash

I have problems with globes in Bash. For example:

echo *

Prints all files and folders in the current directory. e.g. (file1 file2 folder1 folder2)

echo */

Prints all folders with the name / after the name. e.g. (folder1 / folder2 /)

How can I only swallow files? e.g. (file1 file2)

I know that this can be done by analyzing ls, but also know that this is a bad idea . I tried using advanced blobbing but couldn't make it work.

+4
source share
3 answers

With any external utility you can try for loopwith glob support:

for i in *; do [ -f "$i" ] && echo "$i"; done
+8
source

, globbing, find:

find . -type f -maxdepth 1
+4

, , bash :

shopt extglob
echo !(*/)

But note that this is actually what corresponds to "dislike directories."
It will still correspond to dangling symbolic links, symbolic links pointing to non-directories, device nodes, fifos, etc.

It will not match symbolic links pointing to directories.

If you want to iterate over normal files and no more, use find -maxdepth 1 -type f.

A safe and reliable way to use it is as follows:

find -maxdepth 1 -type f -print0 | while read -d $'\0' file; do
  printf "%s\n" "$file"
done
+1
source

All Articles