Dax Durax
Dax Durax

Reputation: 1657

chdir to directory with spaces

I am running the following command:

cd $(find /tmp/my_temp/ -type d -wholename '/tmp/my_temp/MyNumb-*_WeCo - MX')

It returns somethingn like this:

/tmp/nolio_temp/MyNumb-15_WeCo - MX

When trying to cd to this output I cannot because there are spaces.

Is there any way to cd to the directory that is returned by find even though there are spaces present?

Upvotes: 0

Views: 998

Answers (3)

Greg Bacon
Greg Bacon

Reputation: 139701

In a comment to fedorqui’s answer, you wrote that you want to avoid using double-quotes in your command. I’m curious to know why, but you can do it, in bash at least, with

eval 'cd '$(find /tmp/nolio_temp -type d \
  -wholename '/tmp/nolio_temp/MyNumb-*_WeCo - MX' |
    sed -e 's/ /\\ /g')

But be very careful of malicious filenames.

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295815

It's a mouthful, but the following is extra paranoid in terms of working correctly in odd corner cases:

IFS= read -r -d '' dirname \
  < <(find /tmp/my_temp/ -type d -wholename '/tmp/my_temp/MyNumb-*_WeCo - MX' -print0)
cd "$dirname"

This will handle filenames ending in whitespace, filenames containing newlines (including trailing newlines, which $() will eat), cases where find returns only one result, and other such oddballs.

Upvotes: 1

fedorqui
fedorqui

Reputation: 290415

Just quote it and it will work:

cd "$()"

In your case:

cd "$(find /tmp/my_temp/ -type d -wholename '/tmp/my_temp/MyNumb-*_WeCo - MX')"

This way you tell cd to use as an argument what is within the double quotes.

Upvotes: 2

Related Questions