如何以管道输出作为cd命令的输入

https://stackoverflow.com/questions/3437514/bash-how-to-pipe-result-from-the-which-command-to-cd

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

posted @ 2022-01-16 10:56  三国梦回  阅读(38)  评论(0编辑  收藏  举报