Run cd in script and stay in that directory - 'source' command not helping
Tried using the answer found here:
How to run 'cd' in shell script and stay there after script finishes?
When I add the 'source' command, the directory is still unchanged after script runs, regardless of whether I 开发者_开发问答execute 'source ' or call the script using an alias coded in cshrc.
Any help is much appreciated!
As you can see below, make sure your call to cd
is not executing within a subshell. If it is, this won't work, source
or not.
Script with cd
in subshell
#!/bin/bash
( cd /etc ) # thie exec's in a subshell
Output
$ pwd
/home/siegex
$ source ./cdafterend.sh && pwd
/home/siegex
Script with cd
not in subshell
#!/bin/bash
cd /etc # no subshell here
Output
$ pwd
/home/siegex
$ source ./cdafterend.sh && pwd
/etc
It was necessary to remove "/bin/" from the cd command within this script, in order for the command to work as intended. Removing this removes the subshell issue for this script. Also, coding "$1" in the ls command was invalid in this context.
精彩评论