views:

721

answers:

9

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 directory /b. I want to start my program running ../a/helloworld and get the hello-world.txt somewhere in a third directory /c.

I thought it's possible to do that with env command, but I could not find how to do that.

A: 

If you always want it to go to /C, use an absolute path when you write the file.

Tom Ritter
A: 

Just cd in your program. When the program exits, you'll be back in your starting directory.

Paul Tomblin
A: 

You should look at the libc filesystem interface Here

LB
A: 

One way to do that is to create a wrapper shell script.

The shell script would change the current directory to /c, then run /a/helloworld. Once the shell script exits, the current directory reverts back to /b.

Here's a bash shell script example:

#!/bin/bash
cd /c
/a/helloworld
Jin Kim
+13  A: 
David Schmitt
Whoops, you gave this answer moments before I did. So +1 to you and I deleted my otherwise duplicate.
Eddie
+1  A: 

sh -c 'cd /c && ../a/helloworld'

mihi
+5  A: 

Similar to David Schmitt's answer, plus Josh's suggestion, but doesn't leave a shell process running:

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

This way is more similar to how you usually run commands on the shell. To see the practical difference, you have to run ps ef from another shell with each solution.

Juliano
Josh Kelley
Good catch Josh, thanks. I'm updating the answer.
Juliano
+1  A: 

If you want to perform this inside your program then I would do something like:

#include <unistd.h>
int main()
{
  if(chdir("/c") < 0 )  
  {
     printf("Failed\n");
     return -1 ;
  }

  // rest of your program...

}
Harold
+1  A: 

I always think UNIX tools should be written as filters, read input from stdin and write output to stdout. If possible you could change your helloworld binary to write the contents of the text file to stdout rather than a specific file. That way you can use the shell to write your file anywhere.

$ cd ~/b

$ ~/a/helloworld > ~/c/helloworld.txt

Luther Blisset
+1 for being right, although the answer is only peripherally an answer.
David Schmitt