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 redirection the output of a command to "cd"? For example, I have searched for a directory using locate and got the path to it. Now, instead of writing cd path, can I redirect the output to cd?

I've tried this:

oliver@nell:~$ locate Descargas | grep Descargas$
/home/oliver/Descargas
oliver@nell:~$ locate Descargas | grep Descargas$ | cd
oliver@nell:~$ locate Descargas | grep Descargas$ > cd
oliver@nell:~$ locate Descargas | grep Descargas$ < cd
/home/oliver/Descargas
oliver@nell:~$ 

But no luck. It probably isn't something very useful but I'm curious

Thanks

share|improve this question

1 Answer 1

up vote 13 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.