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

How can I change bash directory from C++ program?

本文关键字:bash 目录 C++ 程序      更新时间:2023-10-16

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

#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";
    }
}

但是你不能用 bash 写

cd $(a.out)

因为很多原因。一个原因是a.out具有更多的输出,而不仅仅是生成的目录路径。

在这种情况下,如何更改调用进程的当前目录(bash(?特定于Linux的方式是可以的。当然,将目录路径输出到一个文件(在虚拟硬盘中(并从bash读取它可以实现我想要什么,但我认为这不是一个明智的方法。


相关:通过C++程序更改 shell 的目录


补充:

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

#include <iostream>
using std::cout;
using std::cin;
int main(int argc, char **argv) {
    if (argc == 1) {
        //print directory paths with index
    } else {
        unsigned index = atoi(argv[1]);
        switch (index) {
            case 0:
                cout << "/home/user/foo"; break;
            case 1:
                cout << "/home/user/bar"; break;
            default:
                cout << "/home/user";
        }
    }
}

,然后我可以写

./a.out
reply -p "Input index: "
cd $(a.out $REPLY)

但这并不简单(肮脏(,并且使程序更加复杂。

选项 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}]

我刚刚找到了答案。

man bash

命令替换

(截图(

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

因此,可以将所有cout替换为最后一个(带有using std::cerr;(以外的cerr