Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

linux - bash - how to pipe result from the which command to cd

How could I pipe the result from a which command to cd?

This is what I am trying to do:

which oracle | cd
cd < which oracle

But none of them works.

Is there a way to achieve this (rather than copy/paste of course)?

Edit : on second thought, this command would fail, because the destination file is NOT a folder/directory.

So I am thinking and working out a better way to get rid of the trailing "/oracle" part now (sed or awk, or even Perl) :)

Edit : Okay that's what I've got in the end:

cd `which oracle | sed 's//oracle//g'`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You use pipe in cases where the command expects parameters from the standard input. ( More on this ).

With cd command that is not the case. The directory is the command argument. In such case, you can use command substitution. Use backticks or $(...) to evaluate the command, store it into variable..

path=`which oracle`
echo $path # just for debug
cd $path

although it can be done in a much simpler way:

cd `which oracle` 

or if your path has special characters

cd "`which oracle`"

or

cd $(which oracle)

which is equivalent to backtick notation, but is recommended (backticks can be confused with apostrophes)

.. but it looks like you want:

cd $(dirname $(which oracle))

(which shows you that you can use nesting easily)

$(...) (as well as backticks) work also in double-quoted strings, which helps when the result may eventually contain spaces..

cd "$(dirname "$(which oracle)")"

(Note that both outputs require a set of double quotes.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...