4

So im trying to create a script that looks in a folder and finds all the file types that have .cpp and run g++ on them. so far i have but it doesn't run it says unexpected end

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

Thanks

1
  • What shell are you using, and on which operating system? Commented Oct 12, 2013 at 0:09

6 Answers 6

4

The problem with your code is that the wildcard * is being expanded by the shell before being passed to find. Quote it thusly:

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

xargs as suggested by others is a good solution for this problem, though.

Sign up to request clarification or add additional context in comments.

Comments

3

find has an option for doing exactly that:

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

Comments

1

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

5 Comments

./bashscript.sh: line 2: $'\r': command not found ./bashscript.sh: line 18: syntax error: unexpected end of file
What are the names of your files?
@user2872510 Are you on cygwin? Possible Windows \r\n line feeds in script?
Your code worked because you were lucky/unlucky enough not to have any *.cpp files in your home directory, so *.cpp was passed unmolested through to find.
Ooh. I knew that it was some wildcard.
1

You could use xargs like:

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

Or if you want to handle files which contain whitespaces:

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

Comments

1

I think you want to use xargs:

For example:

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

2 Comments

did you mean to do find twice
No, this was a typo by Bryan.
0

How about using xargs like this:

find $working_dir -type f -name *.cpp | xargs -n 1 g++

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.