Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is it possible to redirect a command's output to cd? For example, I searched for a directory using locate and got the path to it. Now, instead of writing a cd path, can I redirect the locate output to cd?

I tried this:

$ locate Descargas | grep Descargas$
/home/oliver/Descargas
$ locate Descargas | grep Descargas$ | cd
$ locate Descargas | grep Descargas$ > cd
$ locate Descargas | grep Descargas$ < cd
/home/oliver/Descargas
$ 

No luck. This probably isn't particularly useful, but I'm curious.

share|improve this question

1 Answer 1

up vote 15 down vote accepted

You want command substitution, not redirection:

cd "$(locate Descargas | grep -F 'Descargas$')"

The bits between the $( and the ) are run as a command and the output (stripped of any final newline) is substituted into the overall command.

This can also be done with ‘back ticks’ (“`”):

cd "`locate Descargas | grep -F 'Descargas$'`"

The dollar-paren syntax is generally preferred because it is easier to deal with in nested situations:

# contrived
cd "$(grep '^dir: ' "$(locate interesting-places | head -1)" | sed 's/^[^ ]*//')"
share|improve this answer
    
Thanks! I didn't know that functionality –  oli206 Nov 14 '10 at 12:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.