Bash-如何将 which 命令的 result 传送到 cd

如何将 which命令的结果通过管道传送到 cd

这就是我正在努力做的:

which oracle | cd
cd < which oracle

但都不管用。

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

编辑: 转念一想,这个命令可能会失败,因为目标文件不是文件夹/目录

因此,我现在正在考虑并想出一个更好的方法来去除尾随的“/oracle”部分(sed 或 awk,甚至 Perl) :)

编辑: 好了,这就是我最后得到的:

cd `which oracle | sed 's/\/oracle//g'`
50939 次浏览

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

cd `which oracle`

Note those are backticks (generally the key to the left of 1 on a US keyboard)

In response to your edited question, you can strip off the name of the command using dirname:

cd $(dirname `which oracle`)

With dirname to get the directory:

cd $(which oracle | xargs dirname)

EDIT: beware of paths containing spaces, see @anishpatel comment below

You don't need a pipe, you can do what you want using Bash parameter expansion!

Further tip: use "type -P" instead of the external "which" command if you are using Bash.

# test
touch /ls
chmod +x /ls
cmd='ls'
PATH=/:$PATH
if cmdpath="$(type -P "$cmd")" && cmdpath="${cmdpath%/*}" ; then
cd "${cmdpath:-/}" || { echo "Could not cd to: ${cmdpath:-/}"; exit 1; }
else
echo "No such program in PATH search directories: ${cmd}"
exit 1
fi

OK, here a solution that uses correct quoting:

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

Avoid backticks, they are less readable, and always quote process substitutions.

besides good answer above, one thing needs to mention is that cd is a shell builtin, which run in the same process other than new process like ls which is a command.

  1. https://unix.stackexchange.com/questions/50022/why-cant-i-redirect-a-path-name-output-from-one-command-to-cd

  2. http://en.wikipedia.org/wiki/Shell_builtin