[英]How can I change bash directory from C++ program?
我有一個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的方式是可以的。 當然,當然,將目錄路徑輸出到文件(在ramdisk中)並從bash讀取它可以實現我想要的,我不認為這是明智的方式。
補充:
如果我重寫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)
但這並不簡單(臟)並使程序更復雜。
它有點重,但你可以使用
cd $(a.out | awk '{print $NF}')
改變線
cout << "Input index: ";
至
cout << "Input index: \n";
然后使用
cd $(a.out | tail -1)
刪除該行
cout << "Input index: ";
完全使用:
cd $(a.out)
使用一些不同的標記打印所選目錄,並使用它來過濾輸出。
例:
std::cout << "==== " << "/home/user/foo" << std::endl;
break;
然后,在bash
,您可以使用:
cd $(a.out | grep '====' | awk '{print $2}]
我剛剛找到了答案。
根據man bash
,
命令替換
(剪斷)
Bash通過在子shell環境中執行命令並使用命令的標准輸出替換命令替換來執行擴展
因此,除了最后一個cerr
之外,可以用cerr
替換所有cout
( using std::cerr;
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.