Simple question (for you guys, hard for me)

I am trying to exit this script by cd'ing into a particular directory.

#!/bin/bash
/opt/xxx/xxx/d2h $1
fname=$( /opt/xxx/xxx/d2h $1)
cd /opt/xxx1/xxx1
find . -name '*'$fname'*' -ls
cd /opt/xxx1/xxx1

Upon execution, it returns to my home directory (where I am running this script from.

The last line cd/opt/xxx1/xxx1 doesnt work for me and I cant figure out why it isnt.

Any help would be appreciated. Thanks in advance.

Try adding -xv to the end of your first line - the /bin/bash one.

It will run the shell in debug(ish) mode but what is useful is it shows you what the variables are set to. If /opt/XX1/XX1 doesn't exist then your last line effectively becoms just 'cd' - which *will* return you to your $HOME.

Hope this helps

When you run a script, it executes in a subshell. That subshell has its own environment space, so things like $PWD (or any set variable) will be lost. To paraphrase: "What happens in a subshell stays in a subshell."

Therefore, you canot use a script to change the current working directory of your login shell. You could define an alias, or a function, which would run in the current shell. But the script can't do it.

Alternatively "source" the script by running with the "." operator, eg period-space-scriptpath

. scriptpath