tags:

views:

63

answers:

3

i want to make a script (to) that makes it easier for me to enter folders.

so eg. if i type "to apache" i want it to change the current directory to /etc/apache2.

however, when i use the "cd" command inside the script, it seems like it changes the path WITHIN the script, so the path in the shell has not changed.

how could i make this work?

+5  A: 

Use an alias or function, or source the script instead of executing it.

BASH FAQ entry #60.

Ignacio Vazquez-Abrams
+3  A: 

use a function

to_apache(){
  cd /etc/apache
}

put in a file eg mylibrary.sh and whenever you want to use it, source the file. eg

#!/bin/bash
source /path/mylibrary.sh
to_apache
ghostdog74
+1  A: 

As Ignacio said, make it into a function (or perhaps an alias).

The way I tend to do it is have a shell script that creates the function - and the script and the function have the same name. Then once at some point in time, I will source the script ('. funcname') and thereafter I can simply use the function.

I tend to prefer functions to aliases; it is easier to manage arguments etc.

Also, for the specific case of changing directories, I use CDPATH. The trick with using CDPATH is to have the empty entry at the start:

export CDPATH=:/work4/jleffler:/u/jleffler:/work4/jleffler/src:\
/work4/jleffler/src/perl:/work4/jleffler/src/sqltools:/work4/jleffler/lib:\
/work4/jleffler/doc:/u/jleffler/mail:/work4/jleffler/work:/work4/jleffler/ids

On this machine, my main home directory is /work4/jleffler. I can get to most of the relevant sub-directories in one go with 'cd whatever'.

If you don't put the empty entry (or an explicit '.') first, then you can't 'cd' into a sub-directory of the current directory, which is disconcerting at least.

Jonathan Leffler
I don't have any trouble with `cd` into a subdirectory without a leading ":" in CDPATH. (Bash 3.2 or 4.0)
Dennis Williamson
@Dennis: well, it could be a piece of folk lore I picked up from Korn Shell on Unix vs bash; it most certainly was a problem when I first started using it with ksh - but I've not validated whether it is a problem in bash (since what I have works fine in bash).
Jonathan Leffler