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'`
The short answer is: cd doesn't work like that. The longer answer is that in bash, commands in a pipeline are each executed in a subshell. Since cd is a shell builtin, it only affects the shell it's executed in. If you cd within a subshell, the effect will disappear when the subshell exits.
To use bash redirection, you run a command, specify the > or >> operator, and then provide the path of a file you want the output redirected to. > redirects the output of a command to a file, replacing the existing contents of the file.
The Bash shell won't let you use commands such as CD.. or CD Windows. Instead, you will have to enter the CD command followed by a backslash and the name of the folder that you want to access. Therefore, you could get to the root directory by typing CD\.
A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line. Guiding principle #1: Commands executed in Bash receive their standard input from the process that starts them.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With