How do I run a program with a different working di

2019-01-04 15:30发布

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.

11条回答
贼婆χ
2楼-- · 2019-01-04 15:51

from the current directory provide the full path to the script directory to execute the command

/root/server/user/home/bin/script.sh
查看更多
时光不老,我们不散
3楼-- · 2019-01-04 15:55

Just change the last "&&" into ";" and it will cd back no matter if the command fails or succeeds:

cd SOME_PATH && run_some_command ; cd -
查看更多
Summer. ? 凉城
4楼-- · 2019-01-04 15:56

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

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-04 15:58

An option which doesn't require a subshell and is built in to bash

(pushd SOME_PATH && run_stuff; popd)

Demo:

$ pwd
/home/abhijit
$ pushd /tmp # directory changed
$ pwd
/tmp
$ popd
$ pwd
/home/abhijit
查看更多
We Are One
6楼-- · 2019-01-04 16:01

why not keep it simple

cd SOME_PATH && run_some_command && cd -

the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.

查看更多
▲ chillily
7楼-- · 2019-01-04 16:06

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...

}
查看更多
登录 后发表回答