loading...

re: Bash: How To Teleport In The Terminal VIEW POST

FULL DISCUSSION
 

pushd and popd are super handy for jumping to several locations, then trying to backtrack to where you were a few jumps ago; I've known about them for a while and still haven't gotten into the habit of using them.

But for simple one-off cases, just jumping to one directory and the jumping back to the last one, there's another option that I use more often: if you call the cd command with the - character, it jumps back one directory!

> ~/projects/my-thing/src
$ cd ../../my-other-thing/sec

> ~/projects/my-other-thing/src
$ cd -

> ~/projects/my-thing/src
$ 

This only works for a single level; whereas pushd/popd will store as many moves as you want, if you issue cd - a bunch of times, you'll just jump back and forth between the same two directories. But for most of my own day to day uses, it gets the job done. This is especially handy when you weren't planning to jump back, like when you misremember where something is and you cd to the wrong place, then want to jump back to where you were.

Another related protip: the git checkout command adopted the same convention, so that git checkout - will checkout out the previous branch!

 

Maybe worthwile to note that zsh gives you multiple cd - entries and you can even iterate and inspect the list when hitting tab. Quite nice. And then wd plugin for "warp points" (basically cd X aliases, but with convention).

 

Another useful feature of cd, calling it with no arguments takes you to ~. This can save you doing cd ../../../.. or cd ~!

 

A side effect of this that sometimes catches me off guard is that if you try to cd to an environment variable that doesn't exist, or if you misspell a variable (e.g. cd $PORJ_HOME instead of $PROJ_HOME), you end up running plain cd by accident and going home instead! Always takes me a second to realize what happened

 

~- is the value of the shell variable OLDPWD, so you can list out your previous directory with ls ~- . Saves a little time from having to type all the extra characters in cd - && ls && cd - .

But since it holds the actual directory path, it's even more useful because you can quickly list out any subdirs with ls ~-/oldPwdSubDir/anotherSubdir

Code of Conduct Report abuse