tags:

views:

2575

answers:

5

Is there any way to mark a script to be "run as source" so you don't have to add the source or "." command to it every time? i.e., if I write a script called "sup", I'd like to call it as

sup Argument

rather than

source sup Argument

or

. sup Argument

Basically, I'm trying to use cd within a script.

+2  A: 

Create an alias for it:

alias sup=". ~/bin/sup"

Or along those lines.

See also: Why doesn't cd work in a bash shell script?


Answering comment by counter-example: experimentation with Korn Shell on Solaris 10 shows that I can do:

$ pwd
/work1/jleffler
$ echo "cd /work5/atria" > $HOME/bin/yyy
$ alias yyy=". ~/bin/yyy"
$ yyy
$ pwd
/work5/atria
$

Experimentation with Bash (3.00.16) on Solaris 10 also shows the same behaviour.


Jonathan Leffler
Hmm, alias worked, but still executes in a separate shell so the 'cd' within the script does nothing. Thanks though!
Typeoneerror
In that case, probably go with the CDPATH solution in the referenced question? It's what I use mostly. What is actually in the script? Just a 'cd' or a whole lot more stuff?
Jonathan Leffler
+2  A: 
Varkhan
I did modify my CDPATH, but it still doesn't seem to work when the script is executing in its "own" shell
Typeoneerror
Yes, of course, because the change doesn't get propagated to the parent shell, the one that you are using. My remark was more about a way to get rid of the script altogether.
Varkhan
+5  A: 

Bash forks and stars a subshell way before it or your kernel even considers what it's supposed to do in there. It's not something you can "undo". So no, it's impossible.

Thankfully.

Look into bash functions instead:

sup() {
    ...
}

Put that in your ~/.bashrc.

lhunath
A: 

what about when you run the script

./scriptname.sh

I tried running my script using this command but it does not recognize the script. Works fine if I do

scriptname.sh