I am not too deep in the material and rarely use Bash scripts. Even with some research, I couldn't quickly learn everything in Bash so that I could search an entire directory with its sub-directories for files and then output their type. I've now gotten a bit into the direction of functions, but again don't quite know how to do this recursively. Also, I want to consider only files and not folders. Here is something I have already done on my own:
for item in "$1"/*
do
if ! [ -d $item ]; then
echo $(file $item)
fi
done;
So when the script is called, the path is passed as an argument. The path is then searched for non-directories and their type is output with the command file. But how is this recursive and also implementable for sub-directories? I have also tried it by iterating over ls -R, but then names of folders are still appended and I can no longer check via my way if it is a folder or a file. Edit: I can't use find!
I am glad about any help!
CodePudding user response:
You can use bash extended globbing capabilities:
$ shopt -s dotglob globstar
$ for i in **/*; do [ -d "$i" ] && continue; file "$i"; done
CodePudding user response:
This may help: How to recursively list subdirectories in Bash without using "find" or "ls" commands?
That said, I modified it to accept user input as follows:
#!/bin/bash
recurse() {
for i in "$1"/*;do
if [ -d "$i" ];then
echo "dir: $i"
recurse "$i"
elif [ -f "$i" ]; then
echo "file: $i"
fi
done
}
recurse $1
If you didn't want the files portion (which it appears you don't) then just remove the elif and line below it. I left it in as the original post had it also. Hope this helps.
CodePudding user response:
Suggesting
file $(find -type f 2>/dev/null)
Explanation:
find
command that search recursively into current folder.Filter only files from
find
command:-type f
.Ignore any
find
permission/access errors with2>/dev/null
Run
file
command on each found file.