133

I would like to frequently switch between directories that are in totally unrelated paths, for example /Project/Warnest/docs/ and ~/Dropbox/Projects/ds/test/.

But I don't want to type cd /[full-path]/ all the time. Are there any shortcut commands to switch to previously worked directories?

One solution I could think of is to add environment variables to my bash .profile for the frequently used directories and cd to them using those variables.

But is there any other solution to this?

saiy2k
  • 1,593
  • Symbolic links could also be useful for this. http://en.wikipedia.org/wiki/Symbolic_link#POSIX_and_Unix-like_operating_systems – user606723 Feb 09 '12 at 15:11

36 Answers36

147

If you're just switching between two directories, you can use cd - to go back and forth.

Mat
  • 52,586
Chris Card
  • 2,292
66

There is a shell variable CDPATH in bash and ksh and cdpath in zsh:

CDPATH    The search path for the cd command. This is a colon-separated
          list of directories in which the shell looks for destination
          directories specified by the cd command.

So you can set in your ~/.bashrc:

export CDPATH=/Project/Warnest:~/Dropbox/Projects/ds

Then cd docs and cd test will take you to the first found such directory. (I mean, even if a directory with the same name will exist in the current directory, CDPATH will still be consulted. If CDPATH will contain more directories having subdirectories with the given name, the first one will be used.)

manatwork
  • 31,277
  • 17
    It should be mentioned that in general, you'll want the first entry in $CDPATH to be . (an explicitly entry, i.e. : also works). Otherwise you'll end up with the odd behavior where CDPATH dirs take precedence over directories in the current working directory, which you probably do not want. – jw013 Feb 08 '12 at 23:40
  • 4
    I do pretty much the same thing, but without the export. That way, CDPATH is not exported to scripts with potentially weird or harmful effects. See here for more discussion and examples. – Telemachus Feb 17 '12 at 12:47
  • "bash and ksh and cdpath in zsh" ... and in tcsh (just answering a question based on that over on [SU] and found this while looking for similar answers on SE). – Hennes Nov 13 '13 at 07:36
  • This is POSIX-specified, I think. At least, the POSIX for cd refers to it. – mikeserv Aug 30 '14 at 17:47
56

Something else you might try is a tool called autojump. It keeps a database of calls to it's alias (j by default) and attempts to make intelligent decisions about where you want to go. For example if you frequently type:

j ~/Pictures

You can use the following to get there in a pinch:

j Pic

It is available of Debian and Ubuntu, and included on a per-user basis in ~/.bashrc or ~/.zshrc by default.

  • 5
    Autojump is probably the best tool for this, it takes a little while to build up the database of common dirs, but once it does I think you'll find that you can't live without it. I know every time I'm on someone else's computer I feel crippled. – quodlibetor Feb 13 '12 at 18:29
  • 1
    thanks love this tool! And although cd - is handy to know if you don't already know it, I think this is a much better solution than the current top answer. – User Oct 13 '14 at 04:49
  • Installed system-wide on what systems? – ctrl-alt-delor Jan 17 '17 at 16:13
  • 1
    @richard It is available as a package (e.g. apt-get install autojump in Ubuntu, but also for many others as documented on their page) for system-wide installation, but each user needs to load it into their shell environment so it can override cd to keep track of where you're going – nealmcb Apr 06 '17 at 17:56
  • Important to say source /usr/share/autojump/autojump.sh should be added to ~/.bashrc for autojump to work. – Pablo A Jul 10 '17 at 02:10
  • I switched to a new Ubuntu PC. Life without autojump is intolerable. – BenKoshy Aug 02 '18 at 01:32
41

If it's a small number of directories, you can use pushd to rotate between them:

# starting point
$ pwd
/Project/Warnest/docs
# add second dir and change to it
$ pushd ~/Dropbox/Projects/ds/test
~/Dropbox/Projects/ds/test /Project/Warnest/docs
# prove we're in the right place
$ pwd
~/Dropbox/Projects/ds/test
# swap directories
$ pushd
/Project/Warnest/docs ~/Dropbox/Projects/ds/test

unlike cd -, you can use this with more than two directories


Following up on Noach's suggestion, I'm now using this:

function pd()
{
    if [[ $# -ge 1 ]];
    then
        choice="$1"
    else
        dirs -v
        echo -n "? "
        read choice
    fi
    if [[ -n $choice ]];
    then
        declare -i cnum="$choice"
        if [[ $cnum != $choice ]];
        then #choice is not numeric
            choice=$(dirs -v | grep $choice | tail -1 | awk '{print $1}')
            cnum="$choice"
            if [[ -z $choice || $cnum != $choice ]];
            then
                echo "$choice not found"
                return
            fi
        fi
        choice="+$choice"
    fi
    pushd $choice
}

example usage:

# same as pushd +1
$ pd 1

# show a prompt, choose by number
$ pd
 0 ~/Dropbox/Projects/ds/test
 1 /Project/Warnest/docs
 2 /tmp
? 2
/tmp ~/Dropbox/Projects/ds/test /Project/Warnest/docs

# or choose by substring match
$ pd
 0 /tmp
 1 ~/Dropbox/Projects/ds/test
 2 /Project/Warnest/docs
? doc
/Project/Warnest/docs /tmp ~/Dropbox/Projects/ds/test

# substring without prompt
$ pd test
~/Dropbox/Projects/ds/test /Project/Warnest/docs /tmp

etc. Obviously this is just for rotating through the stack and doesn't handle adding new paths - maybe I should rename it.

Useless
  • 4,800
  • 7
    Ooh, I knew about pushd and popd for traversal, but not that pushd could rotate what's been used so far... – Izkata Feb 08 '12 at 20:29
20

I use alias in bashrc to do those cds.
such as:

alias wdoc='cd ~/Project/Warnest/docs'
alias dstest='cd ~/Dropbox/Projects/ds/test'
Felix Yan
  • 673
  • is bashrc a file like .profile? in which I need to add those lines? – saiy2k Feb 08 '12 at 07:43
  • ~/.bashrc or /etc/bash.bashrc. I did not use .profile before, so don't know the relationship between them :-( – Felix Yan Feb 08 '12 at 07:45
  • 1
    scripts bashrc will start everytime you open terminal. profile with startup. –  Feb 08 '12 at 10:42
  • added those lines to my .bash_profile and it works great.. thx :) – saiy2k Feb 08 '12 at 10:56
  • I have several specific project folders i go to regularly, this is the easiest way to set them up and maintain them. Also, for me, it results in the absolute least number of characters typed of all the solutions here. KISS! :-) – moodboom Jun 10 '16 at 12:08
  • 1
    I'd recommand placing aliases in ~/.bash_aliases for maintenance purpose. It requires your .bashrc to be aware of this file, add if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi in your .bashrc (it may already be there) – Sumak Aug 25 '20 at 10:01
15

Use "pushd -n" (assuming you use bash).

Add to your ~/.bashrc:

pushd -n /Project/Warnest/docs/
pushd -n ~/Dropbox/Projects/ds/test/

then,

cd ~ is your home,

cd ~1 is ~/Dropbox/Projects/ds/test/

cd ~2 is /Project/Warnest/docs/

You can use ~1,~2 etc in exactly the same way as ~.

Eelvex
  • 686
12

I found a script (typically called acd_funch.sh) that solved this issue for me. With this you can type cd -- to see the last 10 directories that you've used. It'll look something like this:

0  ~/Documents/onedir
1  ~/Music/anotherdir
2  ~/Music/thirddir
3  ~/etc/etc

To go to ~/Music/thirddir just type cd -2

References

NOTE: This script was originally published in a linux gazette article which is available here: acd_func.sh -- extends bash's CD to keep, display and access history of visited directory names.

slm
  • 369,824
Dean
  • 541
11

Try the cdable_vars shell option in bash. You switch it on with shopt -s cdable_vars.

Then you need to set your variables export dir1=/some/path. and finally cd dir1, etc. You can then put it in your ~/.bashrc to make it stick.

Mat
  • 52,586
Wojtek
  • 2,330
8

There are a lot of good suggestions here. Which to use would depend on whether you have a small fixed list of directories you switch among, or whether you are looking for a more generic solution.

If it's a small fixed list, setting up simple aliases (as Felix Yan suggested) would be easiest to use.

If you're looking for a more generalized solution (i.e. many different directories, changing over time), I'd use pushd and popd (as Useless suggested). I personally find the default pushd/popd to be hard to use, especially as you start switching among many folders; however I wrote a few tweaks that make it much easier for me. Add the following to your bashrc:

alias dirs='dirs -v'
pd () 
{ 
    if [ -n "$1" ]; then
        pushd "${1/#[0-9]*/+$1}";
    else
        pushd;
    fi > /dev/null
}
  • Use pd (as a shorter form of pushd) to jump to a new folder, remembering where you were.
  • Use dirs to see the list of saved directories.
  • Use pd 3 to jump to directory number 3.

Example Usage:

$ PS1='\w\$ '   ## just for demo purposes
~$ pd ~/Documents/data
~/Documents/data$ pd ../spec
~/Documents/spec$ pd ~/Dropbox/Public/
~/Dropbox/Public$ pd /tmp
/tmp$ pd /etc/defaults/
/etc/defaults$ dirs
 0  /etc/defaults
 1  /tmp
 2  ~/Dropbox/Public
 3  ~/Documents/spec
 4  ~/Documents/data
 5  ~
/etc/defaults$ pd 2
~/Dropbox/Public$ dirs
 0  ~/Dropbox/Public
 1  ~/Documents/spec
 2  ~/Documents/data
 3  ~
 4  /etc/defaults
 5  /tmp
~/Dropbox/Public$ pd 4
/etc/defaults$ dirs
 0  /etc/defaults
 1  /tmp
 2  ~/Dropbox/Public
 3  ~/Documents/spec
 4  ~/Documents/data
 5  ~
/etc/defaults$ pd 3
~/Documents/spec$ popd
~/Documents/data ~ /etc/defaults /tmp ~/Dropbox/Public
~/Documents/data$ 
Noach
  • 210
7

The following appeared to work on the one case I tested it on, and you can just drop your directory names as symlinks in ~/Bookmarks:

mkdir "$HOME/Bookmarks"
ln -s /tmp "$HOME/Bookmarks/testdir"

function ccd() { cd $(readlink "$HOME/Bookmarks/$1") ; }

ccd testdir && echo $PWD
# gives /tmp
  • that ccd() function need to typed in the terminal prompt or somewhere else? can u pls explain? – saiy2k Feb 08 '12 at 08:41
  • 1
    @saiy2k: sorry, yes. The function line goes into your .bashrc (you can type it in your terminal to test, but it'll be gone when you close that window), the lines before set up the test case of "testdir" becoming a name for /tmp, and the last line is the test to see if it works. – Ulrich Schwarz Feb 08 '12 at 17:19
7

You could do worse than try j2.

From the README:

Spend a lot of time cd-ing around a complex directory tree?

j keeps track of where you’ve been and how much time you spend there, and provides a convenient way to jump to the directories you actually use.

I use it extensively & recommend it.

6

I also use these aliases (add them to ~/.bashrc):

alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'

It's much quicker to go to the upper directory with them (yet it only solves half of the navigation).

reimai
  • 61
  • 1
    These are helpful aliases, but I'm not entirely sure that they will match the OP's needs. You might consider expanding on your answer to suggest how these might be directly helpful for the OP's issue. – HalosGhost Jul 11 '14 at 18:36
6

I'd advice using zsh, that shell as very good TAB completion for directories, files, and even options for most cli programs.

I've been using that shell for years now, and I'd miss the functionality if it was gone. Scripting the zsh is a lot of fun, too, with a large number of one-liners that can help you every day.

polemon
  • 11,431
  • No need to change to zsh for TAB completeion since bash has it all the same. For other functionality maybe but not for this. – Peer Stritzinger Feb 09 '12 at 11:14
  • 1
    @PeerStritzinger Bash introduced that kind of functionality in BASH 4.0, but compared to zsh, it is still quite far behind. Saying "all the same" is certainly incorrect. – polemon Feb 22 '12 at 00:02
  • Well zsh is ceartainly the übershell but just for tab completion there is no need to change (question was asked for bash). Besides bash 4.0 was introduced about 3 years ago ... – Peer Stritzinger Feb 22 '12 at 09:45
6

In my experience, the greatest speedup in navigating in a shell is to use its history search functionality. In Bash you can search backwards in your history of commands by pressing Ctrl+R and type in some pattern. That pattern is then matched against previous entries in your history -- may it be cd commands or other operations -- and suggestions are made as you type. Simply hit enter to run the suggested command again. This is called reverse-search-history in Bash and I love it. It saves me a lot of keystrokes and spares my internal memory.

It's a good thing because you only have to remember some smaller part of a command, like Drop or Wa to distinguish between the two history entries cd ~/Dropbox/Projects/ds/test/ and cd /Project/Warnest/docs/.

5

if you're using zsh:

  • you don't have to type cd, just type directory path (/foo/bar/baz<Enter> equals to cd /foo/bar/baz<Enter>)

    requires auto_cd option to be set

  • you can expand abbreviated paths with Tab key (/u/sh/pi<Tab> expands to /usr/share/pixmaps; works for file names as well)
4

You never ever should type full path in shell anyway. You always can use:

soffice /P*/W*/*/mydoc*

instead of

soffice /Project/Warnest/docs/mydoc.odt
gena2x
  • 2,397
  • 1
    This is like tab-completing, but worse in every way – Michael Mrozek May 14 '16 at 18:41
  • You can't do this with tab completing with euqal amount of keypressing unless Project is only file starting with P, etc. Also you have to wait for completion each time, using * you have no need to wait. – gena2x Nov 23 '16 at 12:08
  • I think you have it backwards -- you can't do P* unless Project is the only file starting with P. Tab completion can cycle (by default in most shells; you need to rebind tab to menu-complete in bash), and resolves instantly in simple cases like this, there's no waiting around for it – Michael Mrozek Nov 23 '16 at 15:47
  • Regarding 'you can't do it' - you can, try it, you missing whole point if you think you can't. Try echo /u/b/g++ – gena2x Nov 23 '16 at 17:26
  • After that, try to do same with completion. Measure how much time you spent. /ur/b/g++ - 13 keypresses, and some confusion. /u//g++ - 9 keypresses. almost 50% faster to type. – gena2x Nov 23 '16 at 17:33
  • Another problem with completion is that you can't do things like /abc/ject/my*.odt – gena2x Nov 23 '16 at 17:37
  • 1
    I understand what you mean, it's faster as long as you're sure you've typed an unambiguous path, but something like /P*/W*/*/mydoc* sounds like it would work fine until one day you happened to make another file that matches that glob, and suddenly you end up opening both at once. /u*/*/g++ is impressively few characters, but hopefully nothing else in any of the subfolders of any of my root folders starting with u is named g++. (As a nice compromise, in some shells you can use tab to expand globs in-place as you go) – Michael Mrozek Nov 23 '16 at 17:42
  • Right. Now, imagine you making 'mistake' in 5% of cases and have to fallback to tab-completion. You still have a great benefit of typing less in 95% of the cases. And if you really know your system well, you usually also know that there is nothing else starting with u in / and there is no other g++ anythere in /usr. – gena2x Nov 24 '16 at 18:17
4

There is a rather nice tool for quick directory changes:

xd - eXtra fast Directory changer http://xd-home.sourceforge.net/xdman.html

a bit awkward is that you need to map it in bash profile or similar as it only outputs the directory

# function to do `cd` using `xd`
# -g turns generalized directory search command processing on
# which improves the whole thing a bit
f() 
{
        cd `/usr/bin/xd -g $*`
}

you can do things like:

# change to /var/log/a* (gives you a list to choose from)    
f vla
# to skip the list and go directly to /var/log/apache2
f vlapach
null
  • 41
  • 1
  • Change the function to f() { cd "$(xd -g "$@")"; } to properly handle spaced directories and spaces in the arguments to xd (you probably don't need the path). If you never use xd in another manner, you can alternatively do xd() { cd "$(command xd -g "$@")"; } (alternatively, use /usr/bin/xd in place of command xd – you can always run command xd … if you need to bypass it). – Adam Katz Jun 05 '19 at 15:17
3

Try https://pypi.org/project/fastcd/ It sets hook that records visited directories from bash. And sets script as "j" alias, that shows you the last visited directories, with the ability to quickly cd (start typing to filter directories).

  • How does this work? If it's aliases, what does this tool do for you that you can't do by manually editing .bashrc? – G-Man Says 'Reinstate Monica' Nov 03 '14 at 22:55
  • It launches daemon that records visited directories in ~/.fastcd for launched shells(bash). "j" launches tool that shows you the last visited directories, with the ability to quickly cd. Modification of .bashrc is required to make the "j" alias. You can see source code for more information, i guess – Sam Toliman Nov 03 '14 at 23:36
  • Thanks for your quick response. This is the sort of information that should be in the answer. Please [edit] your answer to include this info. – G-Man Says 'Reinstate Monica' Nov 04 '14 at 15:21
3

Update (2016): I now use FASD for this, which allows fuzzy search based on your latest directories.


I've created a tool for this, in Ruby. It allows you to use YAML files to declare your projects.

I've wrote a little article about it here: http://jrnv.nl/switching-projects-terminal-quickly/

I've also posted the source on GitHub: https://github.com/jeroenvisser101/project-switcher

3

I had the same question, and first found this answer. I installed the utility z (https://github.com/rupa/z).

This is exactly what you look for, because z learns from your cd commands, and keeps track of the directories according to the frecency principle (frequent & recent). So after you do both cd commands once, you can do somtehing like:

z docs
z ds

to jump to /Project/Warnest/docs/ and ~/Dropbox/Projects/ds/test/ respectively. The arguments to z are regexes, so you don't even need to type a full folder name.

saroele
  • 213
3

There's also OLDPWD, an environment variable which, according to IEEE 1003.1 (POSIX), should be updated with the previous working directory each time cd changes the working directory (for the curious ones, line 80244 of page 2506 of IEEE 1003.1-2008).

njsg
  • 13,495
3

There is also a "wcd" app created specifically for this (also ported to cygwin, since I am on that). You can create shortcuts, bookmarks of dirs with it. Also supports wild cards. Reading the man page & docs in /usr/share/wcd should help a lot.

http://manpages.ubuntu.com/manpages/hardy/man7/wcd.7.html

sam
  • 31
3

cdargs is the most efficient tool for bookmarking a directory: http://www.youtube.com/watch?v=uWB2FIQlzZg

Emon
  • 61
2

I've been using my own utility cdhist to manage this for many years. It aliases your cd command and automatically keeps a directory stack.

agc
  • 7,223
2

It seems that what you need is basically a project file for your workflow. With directories that belong to your activity, like in a programming IDE. Try Zsh Navigation Tools and the tool n-cd there. It will allow you to navigate across last visited folders and also define a Hotlist with directories of your choice:

n-cd

n-cd can be bound to a key combination with:

zle -N znt-cd-widget

bindkey "^T" znt-cd-widget

2

TL;DR

  1. Use an Fish for interactive shell that empower you immediately (fish>zsh>bash).
  2. Use POSIX/Bash for scripting that is the most widely supported syntax (POSIX>Bash>Zsh>Fish).

Shells

Having tested different shells here is my feedback (in order of testing/adoption):

  • Bash:
    • auto-completion: basic ;
    • path expansion: no ;
    • scripting: excellent.
  • Zsh+oh-my-zsh:
    • auto-completion: good (cycling through);
    • path expansion: yes (cd /e/x1cd /etc/X11/) ;
    • scripting: good.
  • Fish+oh-my-fish (current) is the best out of the box:
    • auto-completion: native and supported options;
    • path expansion: yes ;
    • scripting: too much difference from POSIX-compatible.

Use meaningful aliases

Every shell can be expanded using function and alias, here are the ones I use related to your issue (POSIX-compatible):

back () {  # go to previous visited directory
        cd - || exit
}

up () {  # go to parent directory
        cd ..|| exit
}

There are basic, but really meaningful so easy to remember and autocomplete.

Know your shell

Configure CDPATH to add your most used directories (e.g. ~/projects/, /etc/init.d/) so you can quickly jump to them.

See manatwork answer for mroe details on CDPATH.

Hangout and read

Édouard Lopez
  • 1,332
  • 1
  • 12
  • 23
  • When a shell function calls exit, you exit the interactive shell. Those "meaningful aliases" could just be alias back='cd -' and alias up='cd ..' — but don't worry, those commands will never return false (no previous directory? it sends you home! already in root? it's a no-op!) and therefore you'll never exit. Also consider alias back='cd $OLDPWD' (note the single quotes) since it won't have any output (cd - tells you where it is sending you, which is likely unnecessary since your prompt has that info) – Adam Katz Mar 07 '19 at 16:03
2

You can use export to assign your directory paths to variables and then reference them.

export dir1=/Project/Warnest/docs/
export dir2= ~/Dropbox/Projects/ds/test/
cd $dir1
cd $dir2
andcoz
  • 17,130
  • Yes, this is sufficient for a few favorite dirs. No need to install any other utilities. Just put the export statements in your ~/.bashrc, and they'll always be available. – wisbucky May 21 '18 at 21:44
1

I never did like pushd and popd because they require foresight. Screw that, let's just keep track of the last several directories on our own and then make them available with a cd-to-old-dirs function. I call it cdo.

Put these two code blocks into your rc file (e.g. ~/.bashrc or ~/.zshrc):

# cdo: smarter directory history management
function precmd() { __cdo_log; }    # to install in zsh, harmless in bash
PROMPT_COMMAND="__cdo_log"          # to install in bash, harmless in zsh

# Populate the array DIRHIST with the last 9 dirs visited (not for direct use)
_cdo_log() {
  local d dh first=true
  if [[ -d "$__DIRHIST" && "$__DIRHIST" != "$PWD" ]]; then
    # $__DIRHIST is the last dir we saw, but we miss foo in `cd foo; cd bar`
    # so we use $OLDPWD to catch it; so you'd need a THIRD change to fool us.
    for d in "$__DIRHIST" "${DIRHIST[@]}"; do
      if [[ -n "$first" ]]; then unset DIRHIST first; DIRHIST[1]="$OLDPWD"; fi
      if [[ "$OLDPWD" == "$d" || "$PWD" == "$d" || ! -d "$d" ]]; then
        continue
      fi
      dh=$((1+${#DIRHIST[@]}))
      [ $dh -lt 9 ] && DIRHIST[$dh]="$d" # push up to eight directories
    done
  elif [ -z "$__DIRHIST" ]; then
    DIRHIST[1]="$OLDPWD"
  fi
  __DIRHIST="$PWD"
}

# zsh completion
command -v _describe >/dev/null 2>&1 && compdef _cdo cdo && _cdo() {
  local -a dh
  local d i=1
  for d in "${DIRHIST[@]}"; do dh+=("$((i++)):$d"); done
  _describe 'directory history' dh
}

This maintains a list of your eight more recently used directories (plus the current directory makes nine). I chose 8 because it wraps more nicely when you request a listing.

Bash completion doesn't have descriptions and there's nothing to complete since these are all a single character (do you really want a list of 1-8 digits?) but Z-shell completion is different. See below the code for an example.

Now the function itself:

cdo() {
  local d n=0 t='~' error="Usage: cdo [NUM|ls]"
  if [[ "$1" == ls ]]; then
    for d in "${DIRHIST[@]}"; do echo "$((n=n+1)) <${d/$HOME/$t}>"; done \
      |column |GREP_COLORS='ms=0;32' grep --color -e '\b[0-9] <' -e '>'
  elif [[ 0 -eq "$#" || 0 -eq ${#DIRHIST[@]} ]]; then
    cd ${OLDPWD+"$OLDPWD"}
  elif test "$1" -le "${#DIRHIST[@]}" 2>/dev/null; then # zsh [[ ]] breaks here
    cd "${DIRHIST[$1]}"
  elif [[ -d "$1" ]]; then
    cd "$1"
  else
    test "$1" -gt "${#DIRHIST[@]}" 2>/dev/null \
      && error="cdo log only has ${#DIRHIST[@]} items, try \`cdo ls\`"
    echo "$error" >&2 && return 2
  fi
}

This is basically a switch statement. First, we see if it's a listing request (cdo ls). In that case, we'll loop through the list and number them, then we use column to push it into columns. Coloring the numbers and braces dark green (0;32) with grep is convenient because it has to run after column (otherwise the widths will be off from the colors' control characters).

Second, if we're given zero arguments or there is no saved history, just use $OLDPWD or else go to the home directory if $OLDPWD is blank.

Third, see if we have a number that's no higher than the history's size (errors from being given a directory will silently fail this condition). Go to that directory number.

If it's a directory, go there. Order is important; given cdo 8 with a history of six items but a directory named 8 will just go to that directory.

Finally, we have our errors. Either we say the number is too high or we give the usage, returning with error code 2 (typically used to denote invalid arguments).


The following example uses a prompt of hash directory dollar (# dir $), chosen because Stack Overflow will make prompts gray:

# ~ $ cd /tmp
# /tmp $ cdo
# ~ $ cdo ls
1 </tmp>
# ~ $ cd /
# / $ cdo ls
1 </home/adam>  2 </tmp>
# / $ cdo
# ~ $ cdo ls
1 </>   2 </tmp>
# ~ $ cdo 2
# /tmp $ cd test
# /tmp/test $ cd ../test2
# /tmp/test2 $ cdo ls
1 </tmp/test>   3 </home/adam>
2 </tmp>        4 </>
# /tmp/test2 $ cdo 4
# / $ cd
# ~ $ cdo ls
1 </>           3 </tmp/test>
2 </tmp/test2>  4 </tmp>

Here's what the zsh tab completion looks like (pretend <tab> is a Tab keypress):

# ~ $ cdo <tab>
directory history
1  -- /
2  -- /tmp/test2
3  -- /tmp/test
4  -- /tmp

It's really neat to see that other people have had the same general idea as me (I thought I had been original!). @SamTroliman's mention of fastcd, @null's xd, and @phildobbin's j2 all look quite similar. See also duplicate question 84445, which has a zsh answer using setopt auto_pushd. I still prefer my own code, but ymmv.

Adam Katz
  • 3,965
1

anc is a cmd line tool (short for anchor), that keeps bookmarks of directories. (so far only tested with bash)

In your case:

anc a /Project/Warnest/docs/ ~/Dropbox/Projects/ds/test/

this adds both directories to the anchor(think bookmarks) list

now if you want to jump to /Project/Warnest/docs/ from anywhere on your system type:

anc Warn

and if you want to jump to ~/Dropbox/Projects/ds/test/ type:

anc ds test

Apart from matching text against the bookmarked paths anc has many other convenient ways for jumping around directories.

anc i

starts the interactive mode, that lists all bookmarks by number, so all you have to type is the number

If you type:

anc Pro[TAB]

a list matching all bookmarks (in your case both bookmarks) gets shown and you can select from it using your arrow keys, this is a very quick and intuitive way.

Get anc at the project's github page: https://github.com/tobimensch/anc

There's also a README with example usage.

Full disclosure: I'm the author of this script. I hope some people will find it useful.

JigglyNaga
  • 7,886
1

Some suggestions here:

Most direct idea, I will add alias in the .profile file

vi ~/.profile
alias dir1='cd /myhome/onedir'
alias dir2='cd /jimmy/anotherdir'

Then use $ dir1 or dir2, can cd

If you are always switching in two dirs only. using cd - will switch between them.

Kevin
  • 40,767
Dan
  • 141
1

The solution I use for this situation is screen. Start screen and create a window for each directory with C-a c and navigate there. Change between windows/directories with C-a n or C-a p. Name the windows with C-a A. Then you can pop up a list of your windows with C-a " and navigate using the window number or name. Since it is screen, you can detach from the session saving your work space and re-attach later with the same set up.

0

Based on your criteria, I think simply defining an alias for each frequently used path in your ~/.bashrc is the way to go. I use this method personally.

alias taxes='cd /users/bob/documents/home/finances/taxes'
alias elvis='cd /dropbox/2016/files/music/elvis'

As I mentioned for a related question (link), if you've gone down the directory tree and want to go back up, .. is my personal favorite. You can jump around within a branch of the tree quite easily with .. going up one directory and ../.. two and ../../.. three, etc. You can also go up and down a different branch with the same command, such as cd ../../example or cd ../../../example/example etc. For a simple switch that goes back and forth between directories, cd - or $OLDPWD are your best bets.

0

I have implemented 2 bash functions:

cdh (cd history): it auto-remembers the last 9 directories und you can back to one of them by entering the number.

cdb (cd bookmarks): you can assign any character to the current directory and later go to this directory by entering this character.

cdh and cdb both work with autocd (aka "cd witout cd").

See http://fex.belwue.de/fstools/bash.html

Framstag
  • 169
0

working directory(wd) from atomic seems to be a good package for this: https://github.com/karlin/working-directory

saiy2k
  • 1,593
0

By far the best solution for rapid directory navigation in bash and zsh terminals is to install z - jump around script. This must-have script came recommended by Google Chrome Devtools developer, Paul Irish, in his 2013 Fluent keynote. I can't live without it.

DESCRIPTION Tracks your most used directories, based on 'frecency'.

After a short learning phase, z will take you to the most 'frecent' directory that matches ALL of the regexes given on the command line, in order.

For example, z foo bar would match /foo/bar but not /bar/foo.

[...]

Frecency is a portmanteau of 'recent' and 'frequency'.

Alxs
  • 2,200
  • 3
  • 21
  • 31
0

I've written a script just for that. Here's the link to it on Github.

Here is an example usage:

Let's add a pev variable first:

$ pev add longpath '/A/very/very/long/path/I/frequently/need'
# output:
# environment variable "pev_longpath" added successfully. "pev show" to see the list of pev variables.

Now let's see a list of pev variables defined so far:

$ pev show
# output:
NAMES VALUES
pev_longpath "/A/very/very/long/path/I/frequently/need"

Then change directory to it:

$ cd $pev_longpath

or copy something into one of its subdirectories:

$ cp somefile $pev_longpath/and/deeper/than/that

In fact, pev variables are no different from other environment variables, they're just probably easier to manage. Please feel free to tell me my errors since I don't have much experience with shell scripting. HTH.

aderchox
  • 691