Please use [code][/code]
tags around your code, to preserve formatting and to improve readability.
This issue really requires a bit of explanation.
The point to remember is that changes to a shell's environment always affect only
When you run a subshell/sub-process, it will make a copy of the containing shell's environment. Other commands can then change that sub-process' environment, but it can never affect the environment of the processes above it. It would be a big security risk, for one thing.
So in the above example, the script runs in its own subshell, so it starts with a copy of the first shell's pwd, which is then changed to xxx by the cd command. But when the script exits, you're back in the starting shell, which never had its pwd touched.
's solution involves sourcing
the script, rather than running it. Instead of executing the script as a sub-process, it sucks the commands it contains into the current shell's environment and executes them there.
Depending on what your actual purpose is, another option would be to put your commands inside a shell function instead of a stand-alone script. Since functions sit inside the current environment, the commands they run can affect it directly.
Then anytime you issue the change_dir
command, it will cd the shell into the xxx directory. Put the function inside your bashrc or a similar start-up file if you want to make it permanent (your start-up files are automatically sourced when the shell starts).
PS: The directories used by pushd
can only be directly added to or removed by those commands, although you can also make direct alterations to existing entries in the DIRSTACK
array variable. See the bash manpage entries for each of these commands. And no, root permission is not a factor in manipulating them. The su/sudo commands also fork off new subprocesses, so anything done as root will likewise only affect the root user's environment, leading to the same situation as above.