1

I have the following code:

NSString *currentpath;

NSFileManager *filemgr = [NSFileManager defaultManager];
[filemgr changeCurrentDirectoryPath:@"/Users/BestUser/Downloads"];


currentpath = [filemgr currentDirectoryPath];
NSLog (@"Current directory is %@", currentpath);

When I run it in the terminal, it logs that the path was changed to the directory Downloads.

But the my current directory in the terminal does not change.

Is there a way to change the directory in terminal via objective-c?

Carol Ward
  • 699
  • 4
  • 17
  • What terminal are you talking about? How is your script related to *some* terminal? – luk2302 Nov 27 '19 at 15:07
  • A terminal for macOS. In terminal, if I execute the compiled m file, ./ChangeDirectory, it doesn't change the directory in the terminal. How do I change the directory so that it reflects in the terminal? – Carol Ward Nov 27 '19 at 15:11

3 Answers3

2

Every process has its own working directory, that is, PWD environment variable. When you executing a command like ./ChangeDirectory in current shell session, it starts another subshell which is a process for that command, not all the environment variables will be initialized to the subshell session, PWD is that one.

When you changed the current working directory / PWD variable in subshell, the new variable won't affect the parent process's environment. That makes your not changed.

Itachi
  • 5,777
  • 2
  • 37
  • 69
0

There are two different things potentially stopping this from working the way you describe.

First, -[NSFileManager changeCurrentDirectoryPath:] may return NO, indicating that it was unable to change the current directory as requested. This could happen because the path doesn't exist, or is otherwise inaccessible — and on macOS 10.15 Catalina, some paths (like Downloads) may be inaccessible to scripts as a security measure. Your code should check the return value of that method and handle the error case.

Second, even if you're not running Catalina or pick a folder that is accessible, running the compiled program in a shell won't change the current directory in that shell. This is deliberate behavior on the part of bash and similar shells, as described in several other questions — your call changes the working directory for your process, but that change does not propagate to the parent process. (The last question linked there describes a way to get around this, but its author recommends against using that strategy.)

Tim
  • 59,527
  • 19
  • 156
  • 165
0

Your Code will change current directory for its own process. Also even if you change current directory in terminal - that change will be true only for one terminal sessions.

What is the objective? Are you trying to set current directory at system launch? Or are you trying to store files to a specific directory? There can be many ways to achieve that but you have to elaborate your exact requirement.

Shakir Zareen
  • 232
  • 3
  • 15