Question

A while ago I wrote a script (let's call it myScript) so that it would cd into a specific folder. I saved it in cygwin home directory so I could run it just by calling ~/myScript. I had problems with it, but got it working by calling

. ~/myScript

I have written a parent script (let's call it parentScript) that does few tasks and wanted to add an option so it would cd to my specific directory by calling myScript inside it.

myScript looks something like this:

cd /cygdrive/c/Users/USER_NAME

parentScript has this:

if [ "${1}" -eq CD_TO_USER_NAME_OPTION ]; then
   . ~/myScript
fi

This gives me the same problem I had before with myScript. It cds in the subshell, but then exits leaving me in the directory I started with. I want to be able to run myScript without using the parent that's why I didn't put in parentScript (like grep -E and Egrep). What am I doing wrong??

Was it helpful?

Solution

You would need to invoke parentScript by sourcing it as well:

. parentScript

Then, in whatever script contains that, you would need to make sure the first argument is

./grandparentScript CD_TO_USER_NAME_OPTION

A script invoked by any other means besides sourcing is run in a new process. A process has its own current working directory (man 3 getcwd). That directory is inherited from the parent process, but the parent doesn't get it from the child when the child exits. The only way to have an inner script change the working directory of an outer script is by running them in the same process. That is done most simply by sourcing, or the . command, as you've discovered.

Another solution would be to use a shell function for your directory change:

magicCd() {
    cd my/special/place
}

However, to avoid mixing procedural code with data, maybe the best choice would be simply to use the builtin cd command and store the desired destination in a variable.

my_special_place="$HOME/my/special/place"

cd "$my_special_place"

This last is just as abstract as the sourced script, function or alias, and much more obvious to any maintenance programmer who comes along.

OTHER TIPS

This would be better done via an alias than a shell script:

$ alias myscript="cd /to/some/directory"

Then executing myscript will put you in that directory:

$ myscript
$ pwd
/to/some/directory
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top