Using a Linux shell, how do I start a program with a different working directory from the current working directory?
For example, I have a binary file helloworld that creates the file hello-world.txt in the current directory.
This file is inside of directory /a.
Currently, I am in the directory /b. I want to start my program running ../a/helloworld and get the hello-world.txt somewhere in a third directory /c.
Call the program like this:
The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to
/c, then executeshelloworldfrom/a. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled
/c, make the execution ofhelloworldconditional:Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call
helloworldvia exec:[Thanks to Josh and Juliano for giving tips on improving this answer!]