Bash loop through directory including hidden file

I am looking for a way to make a simple loop in bash on top of everything in my directory, i.e. files, directories and links, including hidden ones.

I would prefer if it can be specifically in bash, but it should be the most general. Of course, file names (and directory names) can have spaces, interrupt lines, characters. Everything except "/" and ASCII NULL (0 × 0), even with the first character. In addition, the result should exclude ".". and "..".

Here is the file generator that you have to deal with in a loop:

#!/bin/bash
mkdir -p test
cd test
touch A 1 ! "hello world" \$\"sym.dat .hidden " start with space" $'\n start with a newline' 
mkdir -p ". hidden with space" $'My Personal\nDirectory'

So, my loop should look (but have to deal with the complicated things above):

for i in * ;
  echo ">$i<"
done

My nearest attempt was to use an array lsand bash, but it does not work with:

IFS=$(echo -en "\n\b")
l=( $(ls -A .) )
for i in ${l[@]} ; do
echo ">$i<"
done
unset IFS

Or using bash arrays, but the ".." directory does not exclude:

IFS=$(echo -en "\n\b")
l=( [[:print:]]* .[[:print:]]* )
for i in ${l[@]} ; do
echo ">$i<"
done
unset IFS
+4
4

chepner , , GNU bash GNU find GNU sort...

GNU find -maxdepth. -print0 0x00 , -print.

sort -z 0x00 .

sed, ( GNU find, , ..).

sed, ./ . basename , basename, , .

( sed : 0x00 . , .)

read -z -0, , -d "" IFS.

-r . ( backslash\\nnewline backslashnewline.) , , escape-.

remove_dot_and_dotdot_dirs()
{
    sed \
      -e 's/^[.]\{1,2\}\x00//' \
      -e 's/\x00[.]\{1,2\}\x00/\x00/g'
}

remove_leading_dotslash()
{
    sed \
      -e 's/^[.]\///' \
      -e 's/\x00[.]\//\x00/g'
}

IFS=""
find . -maxdepth 1 -print0 |
  sort -z |
  remove_dot_and_dotdot_dirs |
  remove_leading_dotslash |
  while read -r -d "" filename
  do
      echo "Doing something with file '${filename}'..."
  done
+2

* , ., :

for i in * .[^.]*; do
    echo ">$i<"
done

.[^.]* , ., ., . , .*, . ... - ..foo, ..?* .

+8

find, :

find .

.

, . .. :

find . -type f -printf %P\\n
0

, -

while read line ; do echo $line; done <<< $(ls -a | grep -v -w ".")

, Check the output

0

All Articles