LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   cd keeps snapping back to current directory when called from bash script (http://www.linuxquestions.org/questions/linux-general-1/cd-keeps-snapping-back-to-current-directory-when-called-from-bash-script-357815/)

ghrellin 08-28-2005 01:29 PM

cd keeps snapping back to current directory when called from bash script
 
Here's the script:
Code:

#! /bin/bash -x

if [ -n $1 ]; then
        cd /home/gabe/$1/ && ls
else
        echo "Blah!"
fi

And here's what happens:
Code:

gabe @ tux ~ $ pwd
/home/gabe

gabe @ tux ~ $ ls amarok-svn/
MakeVars.in    README          config.h        configure.in      stamp-h1
Makefile        acinclude.m4    config.h.in      configure.in.bot  subdirs
Makefile.am    aclocal.m4      config.log      configure.in.in
Makefile.am.in  admin/          config.status*  doc/
Makefile.cvs    amarok/          configure*      libtool*
Makefile.in    autom4te.cache/  configure.files  stamp-h.in

gabe @ tux ~ $ script amarok-svn
+ '[' -n amarok-svn/ ']'
+ cd /home/gabe/amarok-svn/
+ ls
MakeVars.in    README          config.h        configure.in      stamp-h1
Makefile        acinclude.m4    config.h.in      configure.in.bot  subdirs
Makefile.am    aclocal.m4      config.log      configure.in.in
Makefile.am.in  admin          config.status    doc
Makefile.cvs    amarok          configure        libtool
Makefile.in    autom4te.cache  configure.files  stamp-h.in

gabe @ tux ~ $ pwd
/home/gabe

So the directory exists, it tells me that it knows it exists, AND it will cd to it in the script and tell me the contents. Yet it always snaps back to the directory it's in when I start the script.

david_ross 08-28-2005 01:32 PM

I'm not sure I see a problem - what are you wanting to happen?

ghrellin 08-28-2005 01:36 PM

Thanks for the quick reply. And in answer to your question, I want it to stay in the directory I pass to the script.

david_ross 08-28-2005 01:40 PM

In that case you will need to source the commands into your current shell and not start a new one. Just run the script like:
. script amarok-svn
or:
source script amarok-svn

dub.wav 08-28-2005 01:46 PM

Scripts are run in a subshell. Only the subshell changes directory.
It will work if you source the script: '. script'

I don't understand what you need this for, but you can create an alias in your .bashrc, like so: alias mycd='. script'

ghrellin 08-28-2005 01:50 PM

RESOLVED
 
Thanks for the tip. I decided to just make it a function in my .bashrc instead, since I use it a lot.


All times are GMT -5. The time now is 08:58 PM.