Bash Script How to find each file in a folder and run a command on it

So, I am trying to create a script that looks in a folder and finds all types of files that have .cpp and run g ++ on them. while I have it, but it doesn’t start it, it says an unexpected end

for i in `find /home/Phil/Programs/Compile -name *.cpp` ; do echo $i ; 
done

thanks

+4
source share
5 answers

The problem with your code is that the wildcard is *expanded by the shell before being passed for search. Reply like this:

for i in `find /home/Phil/Programs/Compile -name '*.cpp'` ; do echo $i ;  done

xargsas suggested by others, is a good solution to this problem.

+4
source

find has the ability to do just that:

find /p/a/t/h -name '*.cpp' -exec g++ {} \;
+3
source

xargs, :

find folder/ -name "*.cpp" | xargs g++

, :

find folder/ -name "*.cpp" -print0 | xargs -0 g++

+1

I think you want to use xargs :

For example:

find /home/Phil/Programs/Compile -name *.cpp | xargs g++
+1
source

This code works for me:

#!/bin/bash

for i in `find /home/administrator/Desktop/testfolder -name *.cpp` ; do echo $i ; 
done

I get:

administrator@Netvista:~$ /home/administrator/Desktop/test.sh
/home/administrator/Desktop/testfolder/main.cpp
/home/administrator/Desktop/testfolder/main2.cpp
+1
source

All Articles