is there anyway to change directories in a script and have it actually work?
when u put something like cd /var/tmp in a script named runner.
when u run that runner script, the current directory is still what it is. it doesn't change to /var/tmp.
what can be done about this?
depends on HOW you execute your 'runner' script.
try prefixing 'runner' with '. ' (dot space):
. runner
you can use cd command itself to change the directory before running the script something like this:
cd /folder/sub folder
. ./script
what is the mean by placing a dot before the script name, when I am learning the shell, I found only if you put dot before the script name, or those command such as ' export variable ' in the shell file would not take effect?
Thanks
. is used run the script in the same process. export works when you use the . before the script. here is an example:
$$ cat try
. ./test
echo $TEST
$$ cat test
export TEST=1
$$ ./try
1
skysmart:
is there anyway to change directories in a script and have it actually work?
when u put something like cd /var/tmp in a script named runner.
when u run that runner script, the current directory is still what it is. it doesn't change to /var/tmp.
what can be done about this?
When you execute a script, it is run in a child process, and a child process cannot affect the environment of its parent.
To change directories, you need to execute cd in the current shell; cd is a shell builtin command, and thus runs in the current shell environment.
To get a script to run in the current shell, you can source it, using the dot command:
. name-of-script
In bash, you can also use the word, source:
source name-of-script
You can also put it into a function.