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'`
With dirname to get the directory:
EDIT: beware of paths containing spaces, see @anishpatel comment below
OK, here a solution that uses correct quoting:
Avoid backticks, they are less readable, and always quote process substitutions.
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..although it can be done in a much simpler way:
or if your path has special characters
or
which is equivalent to backtick notation, but is recommended (backticks can be confused with apostrophes)
.. but it looks like you want:
(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..(Note that both outputs require a set of double quotes.)
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
: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.