如何从C ++程序更改bash目录?

时间:2019-04-13 03:43:31

标签: c++ bash

我有一个C ++程序,该程序最终根据用户输入的索引打印目录路径。

body {
  display: flex;
}

fieldset {
  margin: 0 0 16px;
}

[type="reset"] {
  float: right;
}

但是你不能用bash书写

<form>
  <fieldset>
    <legend>Full Name</legend>
    <input name="name">
  </fieldset>
  <fieldset>
    <legend>Address</legend>
    <input name="address">
  </fieldset>
  <fieldset>
    <legend>Email</legend>
    <input name="email" type="email">
  </fieldset>
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>

由于许多原因。原因之一是#include <iostream> using std::cout; using std::cin; int main() { //SUB-ROUTINE: print directory paths with index, using "complex" algorithm // (so an external command rather than a bash function) // (this sub-routine gives choose-able options to a user) // (please note this sub-routine includes `cout`) unsigned index; cout << "Input index: "; cin >> index; switch (index) { case 0: cout << "/home/user/foo"; break; case 1: cout << "/home/user/bar"; break; default: cout << "/home/user"; } } 的输出不仅仅是生成的目录路径。

在这种情况下,如何更改调用进程的当前目录(cd $(a.out) )?特定于Linux的方式是可以的。虽然,当然,将目录路径输出到文件中(在ramdisk中)并从bash读取它可以实现我想要的功能,但我认为这不是明智的方法。


相关:Changing the directory of the shell through a C++ program


补充:

如果我将C ++程序重写为

a.out

然后我可以写

bash

但这不是直接的(肮脏的),并且会使程序更加复杂。

2 个答案:

答案 0 :(得分:1)

选项1

有点重,但是可以使用

cd $(a.out | awk '{print $NF}')

选项2

更改行

cout << "Input index: ";

cout << "Input index: \n";

然后使用

cd $(a.out | tail -1)

选项3

删除行

cout << "Input index: ";

一并使用:

cd $(a.out)

选项4

使用一些不同的标记打印所选目录,并使用该标记过滤输出。

示例:

std::cout << "==== " << "/home/user/foo" << std::endl;
break;

然后,您可以在bash中使用:

cd $(a.out | grep '====' | awk '{print $2}]

答案 1 :(得分:-1)

我刚刚找到了答案。

根据man bash

  

命令替换

     

(剪裁)

     

Bash通过在子shell环境中执行命令并将命令替换替换为命令的标准输出来执行扩展

因此,除了最后一个(cout)之外,其他人都可以用cerr代替using std::cerr;

相关问题