8

I wanted to make a simple C program to change to my project directory. Its content is as follows:

#include <unistd.h>
int main()
{
    chdir("/home/enedil/projects/algo");
    return 0;
}

I compiled it with following command (pro.c is its file name):

gcc pro.c -o /usr/local/bin/pro

There were no errors nor warnings. But when I run it, it does not change directory. Why?

  • 1
    You could use an alias instead - alias proj='cd ~/enedil/projects/algo' – Michael Durrant Jul 8 '14 at 11:46
  • @MichaelDurrant oh, you meant cd ~/projects/algo? It is an idea! – enedil Jul 8 '14 at 11:48
  • 1
    This is by design! – Thorbjørn Ravn Andersen Jul 8 '14 at 16:01
15

Your program does exactly what you tell it to do: it changes the working directory for itself to /home/enedil/projects/algo. But once it exits, the shell's working directory is restored.

I guess what you want to achieve is to change the working directory of the parent process, i.e. the shell, without resorting to a simple cd. There is a method, but as its author says: don't do it.

  • 8
    Nitpick, but the shell's working directory isn't restored, because it never changed. The shell is simply a process, just like the program is. Each program has it's own working directory. – Patrick Jul 8 '14 at 12:09
  • 1
    @Patrick, true. Conceptually more accurate would be your working directory is restored, in that your process is "restored" (is active in the foreground). – Paul Draper Jul 8 '14 at 15:29
5

The current working directory is local to the process. So, what you want is not possible.

1

You can also use the CDPATH environmental variable. As explained in man bash:

   CDPATH The search path for the cd command.  This is  a  colon-separated
          list  of  directories  in  which the shell looks for destination
          directories specified by the cd  command.   A  sample  value  is
          ".:~:/usr".

So, for example, you could add this line to your ~/.profile:

CDPATH=~/projects

You can now run cd projects from any directory and move to ~/projects.

0

To do this for the shell, use the source command (aliased to .). It will run the application in the context of the current shell rather than creating a new shell context. This is how you can set environment variables as well. If you notice all of the startup scripts in /etc/rc.d or /etc/init.d, you will see lots of scripts that are included by other scripts with the command

. /etc/init.d/rcvars

The . causes the script /etc/init.d/rcvars so that anything it changes persists in the current environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.