使用Linux shell,如何启动与当前工作目录不同的工作目录的程序?

例如,我有一个二进制文件helloworld,它在当前目录中创建了文件hello-world.txt。 这个文件在目录/a中。

目前,我在目录/b。我想启动我的程序运行..然后在第三个目录/c中获取hello-world.txt。


当前回答

一个不需要子shell并且内置于bash的选项

(pushd SOME_PATH && run_stuff; popd)

演示:

$ pwd
/home/abhijit
$ pushd /tmp # directory changed
$ pwd
/tmp
$ popd
$ pwd
/home/abhijit

其他回答

类似于David Schmitt的回答,加上Josh的建议,但没有让shell进程运行:

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

这种方式更类似于您通常在shell上运行命令的方式。要查看实际的差异,必须在每个解决方案的另一个shell中运行ps ef。

如果您总是希望它到/C,那么在写入文件时使用绝对路径。

从当前目录提供到脚本目录执行命令的完整路径

/root/server/user/home/bin/script.sh

如果你想在你的程序中执行这个,那么我会这样做:

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

  // rest of your program...

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