Is is possible to have argument parser change the terminal directory?

I have a few commands created to help with an internal tool to automate some processes. At the end of some of the commands which open up a smaller module in the project, I would like to have the terminal change directories to a specific directory. Is there a way to accomplish this using ArgumentParser?

If you mean change the working directory of the terminal from where you called your Argument Parser binary, that is not possible on a fundamental system level (not just in Swift) since the binary is being run as a child process of your terminal and cannot change properties of its parent.

If you mean change the working directory of the binary while it’s running so that you can access files in another directory, see FileManager.changeCurrentDirectoryPath.

1 Like

Yeah, I meant the former. I want to change the parent process.

Thanks!

1 Like

As a follow-up, it is still technically possible to achieve your stated result, it just has to be done outside your Swift/Argument Parser binary. If you ask your users to source a shell script (source script.bash vs. ./script.bash), that script then runs as part of the terminal process, and can cd the user’s terminal at will. That means you could have that script run the Swift binary, analyze its output for the directory you want, and cd to it.

Note that it’s probably a bad idea to ask your users to get in the habit of sourcing scripts like that for exactly the same reason as you want to do it (it affects their current terminal process), but it is technically feasible at least.

Terms of Service

Privacy Policy

Cookie Policy