Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using "find" in shell scripting

Tags:

regex

shell

unix

I while back I wrote a shell script that automatically runs a python script over any c++ files it can find in a specified directory. I tested it, it worked fine, and I saved it and forgot about it; problem is I've came back to use it and encountered a problem (turns out I didnt test it enough eh?).

Anyway, the source directory paths I was testing before had no spaces in their names, e.g.

/somedirectory/subfolder/src/

But when I try and run the script using a path with spaces in it, e.g.

/Documents\ and\ Settings/subfolder/src/

It doesnt work.

I've located where the problem is, but I'm not sure how to fix it. Here's the code causing the problem:

names=( $(find "${SOURCE_ROOT_DIRECTORY}" -regex "[A-Za-z0-9]*.*\(cpp\|h\|cc\)$"))

The regular expression works with paths with no spaces, so I'm not sure if there's a problem with the regular expression, or if the "find" command stops when it encounters a space.

Can anyone help?

like image 567
BigStuuu Avatar asked Feb 03 '26 14:02

BigStuuu


1 Answers

find doesn't "stop" when it hits files with spaces in their names. The problem occurs when try to store them as elements in an array.

Change IFS to the newline character (by default it is space):

#change IFS
OLDIFS=$IFS
IFS=$'\n' 

#run find
names=($(find . -regex "[A-Za-z0-9]*.*\(cpp\|h\|cc\)$"))

#restore IFS
IFS=$OLDIFS

#test out the array
echo "size: ${#names[@]}"
for i in "${names[@]}"
do
   echo "$i"
done
like image 176
dogbane Avatar answered Feb 06 '26 06:02

dogbane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!