In terminal, how can I define a key to go to the previous directory which I was in when changing directory with the
For example, I'm in
/opt/soft/bin and I
/etc/squid3 and I want to get back to the first directory.
You can use
or you could use
The other answers are definitely complete in the direct answer sense.
cd - and
cd $OLDPWD are definitely the main choices for this. However, I often find that getting into a workflow with
popd works better.
Long story short, if you are moving into a directory with the ultimate intent of coming back to where you started, use
The major difference is easily shown by an example.
$ cd dir1 $ pushd dir2
At this point, you have a directory stack that is
dir2, dir1. Running
pushd with no arguments will put you back in
dir1 with the stack now as
popd would do the same, but would leave you with an empty directory stack. This is not much different than how you would have been with the
cd - workflow.
However, now you can now change directories multiple times and get back to
dir1. For example,
$ cd dir1 $ pushd dir2 $ cd dir3
If you run
popd at this point, you will go back to
You should use:
it does the same as
cd - (from the currently accepted answer) without the annoying echo of the directory and is easier to type than
cd "$OLDPWD" or
cd - > /dev/null.
$ cd -
will change to the previous working directory.
You can "define a key" for 'cd -' by editing your '~/.bashrc' file and including an alias for the command. For example you could add 'cdc' to make it 'cd -' which would provide you with a shorter way to get to the last directory by adding:
alias cdc='cd -'
This way you would simply type 'cdc' and it would put you in your last working directory.
cd .. goes to the precedent folder in the folder's tree.
cd - goes to the folder which it was before. This command didn't work on some distros (ubuntu 16.04), works in debian 9.