Quote:
Originally posted by zWaR
everything but the line with cd is working OK. Why does cd not work?
I tyed a test also:
Code:
#!/bin/bash
test ()
{
cd $1
}
test $1
and it isnt working.
why not?
|
When you start a script like this a
new shell (sub-) process is created to run your script. The working directory is specific to a shell
process. So changing the working directory with "cd" within a script only has effect for the shell
process that is running the script. When the script ends, the shell process that was created for running the script also ends. And the environment of that process, including the environment variable "$PWD" which holds the working directory, is lost. When the script exits you are back in the shell (process) where you started the script, which has still the same environment as before startinjg the script, so it also still is in the same working directory.
There is a way to work around this. Say, for example, the above script is called, say, "chdir", and is located in /home/zwar/bin. You can then run the script
in the current shell process by starting it with the "source" command (or the dot command (just a single "
. "), which does the same as "source") :
Code:
bash$ source /home/zwar/bin/chdir
or:
bash$ . /home/zwar/bin/chdir
If you want to run your script just by its name, i.e. without "source" or " . ", you can define an alias for it, like this:
Code:
alias chdir='/home/zwar/bin/chdir'
After entering this line at the shell prompt, you can run your script just by typing "chdir". If you want the alias permanently, you can put the alias command in your ~/.bashrc , ~/.profile , /etc/profile. Then the alias will be defined automatically when you log in or start a new shell, depending which file you put it into.
By the way, the name of the alias does not need to have the same name as the script itself, but it is OK.
Hope this helps.