Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a program with a different working directory from current, from Linux shell?

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.

like image 692
Anton Daneyko Avatar asked Apr 24 '09 15:04

Anton Daneyko


People also ask

How do I change the current working directory in Linux?

To change to the current working directory's parent directory, type cd followed by a space and two periods and then press [Enter]. To change to a directory specified by a path name, type cd followed by a space and the path name (e.g., cd /usr/local/lib) and then press [Enter].

How do I change the current directory in shell?

In the shell, the command cd - is a special case that changes the current working directory to the previous working directory by exchanging the values of the variables PWD and OLDPWD. Note: Repeating this command toggles the current working directory between the current and the previous working directory.

How do you run make in a different directory?

Use cd ./dir && make && pwd inside Makefile . The && was exactly what I needed to change a directory and execute a command there, then drop back to the main folder to finish the build.

How do I change the working directory in a script?

Often, you may want to change the current working directory, so that you can access different subdirectories and files. To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.


1 Answers

Call the program like this:

(cd /c; /a/helloworld) 

The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c, then executes helloworld from /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 of helloworld conditional:

(cd /c && /a/helloworld) 

Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld via exec:

(cd /c && exec /a/helloworld) 

[Thanks to Josh and Juliano for giving tips on improving this answer!]

like image 58
David Schmitt Avatar answered Sep 28 '22 17:09

David Schmitt