【问题标题】:c++ bash add to PATHc ++ bash添加到PATH
【发布时间】:2014-06-21 05:13:10
【问题描述】:

我正在尝试制作一个将 export PATH="$PATH:/my/current/directory" 附加到我的 ~/.bash_profile 的可执行文件(我正在使用 g++ 编译 OSX 10.9.2。)现在我只是想让当前的工作目录到达当前的 shell(我想我是用 setenv() 把它放到一个子 shell 中,但我不知道这是否有帮助),我可以从那里拿它。

好的,源代码:

#include <iostream>
#include <string>
using namespace std;
int main(){
  /*Add current directory to path (locally)*/
  string CWD = getenv("PWD");
  string endquote = "\"";
  string mystring = "PATH=\"$PATH:";
  mystring += CWD;
  mystring += endquote;
  // JUST TRYING TO GET THE PATH TO UPDATE IN SHELL
  // WILL EVENTUALLY UPDATE THIS TO GO INTO .bash_profile
  system(mystring);
  system("echo $PATH");
  return 0;
}

和错误:

setup.cpp:11:3: error: no matching function for call to 'system'
  system(mystring);
  ^~~~~~
/usr/include/stdlib.h:177:6: note: candidate function not viable: no known conversion from 'string' (aka 'basic_string<char,
      char_traits<char>, allocator<char> >') to 'const char *' for 1st argument
int      system(const char *) __DARWIN_ALIAS_C(system);
         ^
1 error generated.

构造函数是走这里的路吗(将 const char * 更改为字符串)?我对它们了解不多,但到底是什么,我已经花了几个小时在这上面,所以我还不如多花点时间,对吧?

【问题讨论】:

  • system(mystring.c_str()) 怎么样?
  • 注意子进程不能修改其父进程的环境。可以修改bash启动文件,但不能实际修改环境。
  • @Ernest Friedman-Hill:很高兴知道这一点。

标签: c++ macos bash path


【解决方案1】:

我认为您应该减少对环境变量和外部程序的依赖,而更多地依赖于您可以通过编程方式找到并使用 C++ 库和 POSIX API 进行的操作。在这种情况下,您真的不需要太多:

  • getuid 查找当前用户;
  • getpwuid 查找当前用户的主目录;
  • getcwd 获取当前工作目录;
  • 相当标准的文件输出流的东西。

这个六行程序将export PATH="$PATH:current_working_path" 附加到~/.bash_profile

#include <fstream>
#include <string>
#include <pwd.h>
#include <unistd.h>
#include <sys/param.h>

using namespace std;

int main()
{
    char path[MAXPATHLEN];
    struct passwd* user_info = getpwuid(getuid());
    string user_directory = user_info->pw_dir;
    string current_directory = getcwd(path, sizeof path);

    ofstream bash_profile(user_directory + "/.bash_profile", ios_base::app);
    bash_profile << "export PATH=\"$PATH:" << current_directory << '"' << endl;
}

请注意,这不会影响您从中调用可执行文件的 bash 进程。环境变量是严格继承的:从子进程修改它们不会影响父进程。据我所知,没有办法从子进程中实现这一点。 (允许您操作 bash 进程环境的命令内置在 shell 中,并且不作为单独的进程运行,正是因为这个原因。)

但是,您可以让它在标准输出中打印相同的字符串并使用反引号运行它,或者在运行此程序后运行source ~/.bash_profile

【讨论】:

  • 谢谢,你说得对,我看错了。我昨天才开始搞乱一些 bash 编程,所以我想这就是我的想法。
【解决方案2】:

你需要调用它

 system(mystring.c_str());

system() 函数没有关于std::string 的概念,它需要一个const char* 参数,可以使用c_str() 方法从std::string 获取。

另请注意,应用的system() 命令不会将路径导出到从它启动的(子)shell 之外的任何地方,也不会导出到您的本地配置文件。

要真正实现您的目标,您需要打开并修改您的~/.bashrc 文件(您可以简单地在此处附加另一个export PATH=$PATH:&lt;your stuff&gt; 行)! (更多信息请参见here

【讨论】:

  • 请注意,虽然它会编译并运行,但它不会像您期望的那样。这些命令将在由系统命令启动的子 shell 中执行,它们对启动可执行文件的 shell 没有影响。
  • 是的,我就是这么想的!多谢你们。并且 c_str() 杀死了编译错误,在这一点上,除了功能之外,这对我来说是一个刺……
猜你喜欢
  • 2016-04-12
  • 2010-11-27
  • 2017-08-16
  • 2020-09-01
  • 2021-10-12
  • 1970-01-01
  • 2021-08-15
  • 2016-06-17
  • 2012-12-22
相关资源
最近更新 更多