How do I redirect output to cd?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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/^[^ ]*//')"


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x