开发者

change shell directory from a script?

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 WITHI开发者_开发问答N the script, so the path in the shell has not changed.

how could i make this work?


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

BASH FAQ entry #60.


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


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.


Ignacio Vazquez-Abrams gave a link to what probably answers the question, although I didn't really follow it. The short answer is to use either "source" or a single dot before the command, eg: . to apache

But, I found there are down problems to this if you have a more complicated script. It seems that the original script filename variable ($0) is lost. I see "-bash" instead, so your script can't echo error text that that would include the full filename.

Also, you can't use the "exit" command, or your shell will exit (especially disconcerting from ssh).

Also, the "basename" function gives an error if you use that.

So, it seems to me that a function might be the only way to get around some of these problems, like if you are passing parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜