0

I've been stuck on this for hours:

cd /dir1
(cd $HOME); pwd;

Why does pwd still say /dir1 and didn't go to my home directory?

Jurgen Malinao
  • 149
  • 1
  • 1
  • 5

1 Answers1

2

Parentheses start a subshell: the shell calls fork, and the commands inside the parentheses are executed in the subprocess. The parent process waits for the subprocess to exit then resumes execution. So what's happening is:

  • Execution of cd /dir1: The shell performs chdir("/dir1").
  • Execution of the parentheses: the shell calls fork, then the parent process waits for the child to exit.
  • Execution of cd $HOME: the subshell performs chdir("/home/jurgen").
  • The subshell has run out of commands, so it exits.
  • The subshell has exited, so the wait call in the parent returns.
  • Execution of pwd: the shell prints its current directory, which is /dir1.
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254