1

Possible Duplicate:
Why doesn’t “cd” work in a bash shell script?

Why does cd command in backticks or $(..) never change to the new directory. Any idea how to do it in a single command, that is capture any error and change directory.

[root@linux ~]# pwd
/root
[root@linux ~]# cmdMsg=`cd /tmp 2>&1`
[root@linux ~]# pwd
/root
Community
  • 1
  • 1
r2d2
  • 21
  • 2

4 Answers4

3

Because the backticks spawn a separate process and run separately. So it does cd in that process but doesn't change your current process's working directory.

If you just need to see if the command succeeded and you want to change directory you can check it's exit code:

cd /tmp
retval = $?

if [ $retval -gt 0 ]; then
    echo "cd failed"
fi
Cfreak
  • 19,191
  • 6
  • 49
  • 60
0

because it cd's within the context of the new shell that you opened up to run your cd, try for example:

cmdMsg=`cd /tmp; pwd`
echo $cmdMsg

it will show you that you were in /tmp

hexist
  • 5,151
  • 26
  • 33
0

Separate the commands with with ; if you want to run it all in a single command.

For example:

cd /; ls; cd ~; ls; cd /var; ls

But the problem in your case is that cd is run in a newly spawned shell, which doesn't affect your current shell.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
0

A child process cannot change the environment of its parent process.

pwd
`cd /tmp 2>&1`
pwd
  1. Print working directory in current process.
  2. Create a new child process.
  3. Change to directory /tmp inside the child process (while redirecting stderr to stdout).
  4. Exit the child process.
  5. Print working directory in current process.
Jin Kim
  • 16,562
  • 18
  • 60
  • 86