bash-如何将结果从哪个命令传递到cd [英] bash - how to pipe result from the which command to cd

查看:107
本文介绍了bash-如何将结果从哪个命令传递到cd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将which命令的结果传递给cd?

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

这就是我想要做的:

which oracle | cd
cd < which oracle

但是它们都不起作用.

有没有办法做到这一点(当然不是复制/粘贴)?

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

再三考虑,此命令将失败,因为目标文件不是文件夹/目录.

所以我正在考虑并想出一种更好的方法来摆脱尾随的"/oracle"部分(sed或awk,甚至是Perl):)

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'`

推荐答案

在命令需要来自标准输入的参数的情况下,可以使用管道. (有关此内容的更多信息).

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

使用cd命令不是这种情况.该目录是命令参数.在这种情况下,可以使用命令替换.使用反引号或$(...)评估命令,将其存储到变量中.

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`"

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.)

这篇关于bash-如何将结果从哪个命令传递到cd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆