代码之家  ›  专栏  ›  技术社区  ›  ynn

如何从BC++程序中更改BASH目录?

  •  0
  • ynn  · 技术社区  · 7 年前

    #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)
    

    因为很多原因。一个原因是 a.out 具有比结果目录路径更多的输出。

    bash )? Linux特定的方式是可以的。当然,尽管将目录路径输出到文件(在ramdisk中)并从bash读取它可以实现我想要的,但我认为这不是一个明智的方法。


    Changing the directory of the shell through a C++ program


    补充:

    如果我重写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)
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   R Sahu    7 年前

    方案1

    它有点重,但你可以用它

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

    换条线

    cout << "Input index: ";
    

    cout << "Input index: \n";
    

    然后使用

    cd $(a.out | tail -1)
    

    方案3

    拆下管路

    cout<<“输入索引:”;
    

    cd $(a.out)
    

    方案4

    例子:

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

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

    cd $(a.out | grep '====' | awk '{print $2}]
    
        2
  •  -1
  •   Community Mohan Dere    6 年前

    我刚找到答案。

    根据 man bash ,

    命令替换

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

    所以一个可以取代所有 cout 具有 cerr 除了最后一个(带 using std::cerr; ).

    推荐文章