1. 13

  2. 5

    Also works analogously in git: git checkout - checks out the last branch you were on.

    1. 2

      cd -” has been in my toolbox for a decade, but that is news to me—thank you very much!

    2. 4

      Summary: “cd -” to undo or redo the last cd. Good for switching between two directories or undoing a mistaken cd.

      1. 3

        I occasionally make aliases for commands that need to be executed in a different directory, cd - is a great way to get back to the directory the alias was run in.

        For instance:

        alias command='cd ~/programdir/ && ./command && cd -'
        1. 3

          For something like that, a subshell might be slightly simpler:

          alias command='(cd ~/programdir && ./command)'

          With the subshell, if ./command fails you won’t be left in ~/programdir (whether that’s an advantage or disadvantage is situation-dependent I suppose – perhaps you’d prefer to stick around there to fix things up if something’s gone wrong).

          1. 1

            ah, very cool, didn’t know about subshells. That actually may work better for one of my current aliases. Thanks :)

      2. 4
        1. 4

          zsh has autopushd which turns cd into pushd, so you can always use popd

          1. 1

            I was looking for an equivalent to that option for fish. I found that in fish, “directory history” is always tracked, separately from the “directory stack”. Use prevd and nextd to go forward and back in directory history, and dirh to print the history. The directory stack commands are pushd and popd to move and dirs to print.

          2. 3

            If you find yourself frequently jumping back and forth between directories, have a look at pushd and popd. You can add specific directories to your stack and jump back to them at arbitrary times – not just back to the previous directory! http://www.eriwen.com/bash/pushd-and-popd/

            1. 5

              Pushd and popd are incredibly handy. For the OpenBSD ksh users out there, a basic (useful enough for me) implementation:

              alias d='[ ${#DIRSTACK[@]} -gt 0 ] && for i in `jot ${#DIRSTACK[@]} 1 ${#DIRSTACK[@]} 1`; do echo ${DIRSTACK[$i-1]}; done; echo $PWD'
              alias popd='[ ${#DIRSTACK[@]} -gt 0 ] && { cd "${DIRSTACK[${#DIRSTACK[@]}-1]}"; unset DIRSTACK[${#DIRSTACK[@]}-1]; }; d'
              alias pushd='DIRSTACK[${#DIRSTACK[@]}]="$PWD"; cd'

              (d prints the directory stack)

              1. 3

                For zsh, there’s setopt auto_pushd which I love. Basically it turns every cd into a pushd so that I always have a trail. The small downside is that the stack can get a bit messier, but the upside is that it frees me from having to predict whether I might want to pop back.