keyser
keyser

Reputation: 19189

"find" removing multiple spaces in bash

I have a line in a bash script that searches for a folder using find, and stores its path.

The line is as follows:

findfolder=$(eval echo $(eval "find "$HOME" -iname "$find_regex" -type d -print 2>/dev/null | sort -d | head -1" ))

and it works in almost any case, but, for some reason, if I search for a folder which has two spaces in it, it will return a path where all double spaces have been switched out for single spaces.

So, if I'm searching for a folder called "My music" with two spaces between "My" and "music", it will return "My music" with one space.

If I run the exact same command directly in terminal, I get the correct folder.

Why is this happening? (Let me know if more code is needed. Doesn't seem relevant since I ran the exact same command from terminal though. Don't want wall-of-text for no apparent reason now do we).

edit:

It is now working. The first eval or echo (not sure, but my tests suggests it was eval) was causing the output to collapse, removing "unnecessary" spacing. The working code is:

findfolder="$(eval "find "$HOME" -iname "$find_regex" -type d -print 2>/dev/null | sort -d | head -1" )"

Upvotes: 0

Views: 357

Answers (1)

nosid
nosid

Reputation: 50044

I do not understand what you are trying to do with the eval statements. However, you may experiment with quoting the command substitution. Please note the difference between the following two command lines:

# the two spaces between foo and bar are collapsed
echo $( echo "foo  bar" )

# the two spaces between foo bar bar are kept
echo "$( echo "foo  bar" )"

Upvotes: 3

Related Questions