Home > database >  Find all executable files and copy (along with folder) to some dummy folder using bash
Find all executable files and copy (along with folder) to some dummy folder using bash

Time:06-29

I am trying to collect all executable from folders and trying to copy them into dummy folder. I tried few things using find but some reason it is copying .txt files too

CodePudding user response:

It's really not that simple, you know:

find ./ -executable

On my PC, I get following results:

./20211214/Logs/2021-02-13.log
./20211214/Logs/2021-02-14.log
./20211214/Logs/2021-02-15.log
./20211214/Logs/2021-02-16.log
./20211214/Logs/2021-02-17.log

... which is not that surprising:

ls -ltra 2021-02-17.log
 -rwxrwxrwx 1 usr usr 441793 Feb 26  2021./2021-02-17.log

As you can see: a file with extension "*.log" can be executable.

CodePudding user response:

It is copying txt files too because they are executable... But there are some more issues with your find attempt: it copies directories too, not just files.

And note that you could have several executable files with the same name in different sub-directories of your source directory, e.g., srcFlder/bar/foo and srcFlder/baz/foo. When copying them at destination the last one would overwrite the others.

If you want to copy only executable files that don't have the .txt extension, and you don't care about files with the same name you can try:

find srcFlder -type f -name '*.txt' -prune -o \
  -type f -perm /a x -exec cp -f {} destinationFolder \;

If you have some more file extensions to exclude you can add them with:

find srcFlder -type f \( -name '*.txt' -o -name '*.log' \) -prune -o \
  -type f -perm /a x -exec cp -f {} destinationFolder \;

Finally, if you care about files with the same name, you could preserve the source hierarchy in the destination directory. To do so you must create the target directory (if it does not exist yet) before copying. So, if one of the found files is srcFlder/bar/foo you mkdir -p destinationFolder/bar before copying srcFlder/bar/foo to destinationFolder/bar/foo. Example with a small bash script as exec command:

find srcFlder -type f -name '*.txt' -prune -o \
  -type f -perm /a x -exec bash -c 'f="${1/#srcFlder/destinationFolder}"; \
  mkdir -p $(dirname "$f"); cp "$1" "$f"' _ {} \;
  •  Tags:  
  • bash
  • Related