bash - how to pipe result from the which command t

2019-03-07 18:08发布

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

7条回答
\"骚年 ilove
2楼-- · 2019-03-07 18:29

With dirname to get the directory:

cd $(which oracle | xargs dirname)

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

查看更多
Rolldiameter
3楼-- · 2019-03-07 18:42

OK, here a solution that uses correct quoting:

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

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

查看更多
聊天终结者
4楼-- · 2019-03-07 18:43

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

查看更多
Viruses.
5楼-- · 2019-03-07 18:45
cd `which oracle`

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

查看更多
\"骚年 ilove
6楼-- · 2019-03-07 18:45

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

cd $(dirname `which oracle`)
查看更多
做个烂人
7楼-- · 2019-03-07 18:52

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
查看更多
登录 后发表回答