Is there a command for going back a number of steps in a directory, without using cd?
5,189
Solution 1
Put this in your ~/.bashrc
:
cdup() {
levels=${1-1}
while ((levels--)); do
cd ..
done
}
(The name cdup
comes from the corresponding FTP command, just FYI.)
Solution 2
I was taught to use 'pushd' and 'popd' for such circumstances.
For example, type 'pushd .' and then 'cd /home'. Now type 'popd' and you will be back to where you started.
'pushd'/'popd' is a stack, you can push as many directories on there as you like, but it is last on, first off when you popd.
Solution 3
Sure, why not:
up() { [ $# = 0 ] && cd .. && return [ $1 = 0 ] && return cd .. && up $(($1 - 1)) }
Solution 4
Quick and dirty:
cmd () { dir=.; for i in $(seq 1 $1); do dir=$dir/..; done; pushd $dir; }
Formulated to only change directory once.
Solution 5
Here is an alternative way:
function cdup
{
cd $(for ((i=0 ; i<$1 ;i++)); do printf "../" ; done)
}
Related videos on Youtube
Author by
Admin
Updated on September 18, 2022Comments
-
Admin over 1 year
I'm constantly going 'cd ../../../../'. Is there a command/alias that could let me go 'cmd 4' and I'd be taken back 4 directories?
-
Chris Jester-Young almost 13 years
ls
? Surely you meancd
? -
Admin almost 13 yearsYeah I do, I just wrote this in a rush ;) Editing it now.
-
ypercubeᵀᴹ almost 13 yearsWiil this do?:
alias cmd5 = "cd ../../../../../"
-
-
Chris Jester-Young almost 13 yearsBash isn't tail-recursive, right? You might stack overflow if you do
up 500
. :-) -
Josh Lee almost 13 yearsIf your directories are nested that deeply, you have my sympathies.
-
Admin almost 13 yearsHm, nice. Not heard of that. Doesn't quite fit what I was looking for, but will use that too. Thanks.
-
Chris Jester-Young almost 13 years@Muu: I didn't know this question was a code golf! ;-) BTW, come join us! codegolf.stackexchange.com
-
Admin almost 13 yearsThanks for the response, went with the jleedev's answer due to it being 1 line shorter and I couldn't make up my mind who's to choose! Thanks anyway!
-
Chris Jester-Young almost 13 years@Muu: Both answers will work, but mine will work for many, many levels, and @jleedev's will only work for a small handful (whatever the stack limit is). ;-) (I'm sure you'll never hit the limit either way, but mine is more general, is what I'm trying to get at. :-))
-
Admin almost 13 yearsWasn't planning it to be, but when presented with two bits of code that seem to work as well as each other - you need some kind of criteria! :)
-
Josh Lee almost 13 years@Muu Please remember that recursion is not the proper way to write shell scripts in general.
-
Admin almost 13 yearsFair point, I've awarded you the answer then. Sorry jleedev - though most likely I'll continue using your solution as I'll forget to change it :)