3

I have .bash_aliases with:

alias c1='cd /home/me/code/php'
alias c2='cd /home/me/code/jquery'
alias c3='cd /home/me/code/ruby'
alias c4='cd /home/me/code/c'

How can I DRY this up and loosen the coupling to that entire directory structure?

I have tried:

alias code_base='/home/me/code/'
alias c1='cd code_base/php'
alias c2='cd code_base/jquery'
alias c3='cd code_base/ruby'
alias c4='cd code_base/c'

but I get the error 'is a directory' when I try and use c1 through c4.

I also tried:

alias c1='cd `code_base`/php'

but that didn't work; it gave me:

bash: cd: /php: No such file or directory

I tried alias c1='cd '+work+'/php', but that gave me the directory error too.

2 Answers 2

3

Rather use a variable to define the base directory.

CODE_BASE="/home/me/code/"
alias c1="cd $CODE_BASE/php"
alias c2="cd $CODE_BASE/jquery"
alias c3="cd $CODE_BASE/ruby"
alias c4="cd $CODE_BASE/c"
3
  • Note make sure to use "'s and not ''s Commented Jun 7, 2012 at 3:41
  • @MichaelDurrant You can't use ' here, because $CODE_BASE variable is used inside alias and ' won't let expand this variable. In general case, you can use either ' either ". Both work well.
    – rush
    Commented Jun 7, 2012 at 8:38
  • 1
    Single quotes are fine; substitution of the variable is just delayed until the alias is executed. Commented Jun 7, 2012 at 9:35
3

Besides the answer from mgorven you can also use the CDPATH variable. From man bash:

   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.  A sample value is
          ".:~:/usr".

If you'd set it to CDPATH=.:$HOME/code/ you can just run cd php and would change the directory to $HOME/code/php if the directory exists.

Another solution is to use hashed directories if you are using zsh, e.g:

hash -d code_base=/home/me/code/

Afterwards you can use cd ~code_base/directory to change to a specific directory.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .