Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash loop through directory including hidden file

Tags:

linux

bash

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

I will prefer if it could be specifically in bash but it has to be the most general. Of course, file names (and directory names) can have white space, break line, symbols. Everything but "/" and ASCII NULL (0×0), even at the first character. Also, the result should exclude the '.' and '..' directories.

Here is a generator of files on which the loop has to deal with :

#!/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 like (but has to deal with the tricky stuff above):

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

My closest try was the use of ls and bash array, but it is not working with, is:

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 is not exclude:

IFS=$(echo -en "\n\b")
l=( [[:print:]]* .[[:print:]]* )
for i in ${l[@]} ; do
echo ">$i<"
done
unset IFS
like image 329
Sigmun Avatar asked Oct 15 '14 11:10

Sigmun


People also ask

How do you loop through all the files in a folder in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do you find a hidden file in a directory Linux?

How to View Hidden Files and Directories in Linux. To view hidden files, run the ls command with the -a flag which enables viewing of all files in a directory or -al flag for a long listing of files. From a GUI file manager, go to View and check the option Show Hidden Files to view hidden files or directories.


1 Answers

* doesn't match files beginning with ., so you just need to be explicit:

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

.[^.]* will match all files and directories starting with ., followed by a non-. character, followed by zero or more characters. In other words, it's like the simpler .*, but excludes . and ... If you need to match something like ..foo, then you might add ..?* to the list of patterns.

like image 142
chepner Avatar answered Sep 21 '22 23:09

chepner