这是我的问题。我有一个C++脚本,它将字符串作为消息,将用于提交消息。
这几乎适用于所有情况,但是当<msg>包含转义单引号或双引号时会出现问题,因此命令如下:
git commit -m 'A new message \' with many escaped \" \' quotes \"'所以吉特会感到困惑。
我不想考虑如何在提交消息中转义这些引号,所以我认为最好的方法是避免使用-m标志,即只需执行普通的 <msg> ,并以某种方式将<msg>传递给vi或ed,然后退出并保存。
我的尝试使用ed:
git commit | ed << <msg>vi
git commit | vi << I << <msg> << :wq正如你所看到的,我对linux非常陌生,我没有在网络上找到任何东西来描述我想要做的事情。因此,问题是:在不调用-m 标志的情况下,提交特定消息的正确命令序列是什么?我在这里做错什么了?
发布于 2017-04-02 11:24:57
如果您只是在运行Git,那么根本不要生成一个shell;直接生成git并传递["git", "commit", "-m", message]作为它的argv。在C++中:
#include <string>
extern "C" {
#include <sys/wait.h>
#include <unistd.h>
}
struct child_process {
FILE* file;
pid_t pid;
child_process(FILE* file_, pid_t pid_) :
file(file_),
pid(pid_) {}
};
template<std::size_t n> static child_process popenv(std::string const& path, std::string const (&args)[n]) {
char const* const c_path = path.c_str();
char const* c_argv[n + 2];
c_argv[0] = c_path;
c_argv[n + 1] = NULL;
std::size_t i = 1;
for (std::string const& arg : args) {
c_argv[i++] = arg.c_str();
}
int fds[2];
pipe(fds);
pid_t const pid = fork();
if (pid == -1) {
throw std::system_error(errno, std::system_category());
}
if (pid == 0) {
dup2(fds[1], 1);
execvp(c_path, const_cast<char* const*>(c_argv));
_exit(EXIT_FAILURE);
}
return child_process(fdopen(fds[0], "r"), pid);
}
static int pclosev(child_process const& process) {
int status;
fclose(process.file);
if (waitpid(process.pid, &status, 0) == -1) {
throw std::system_error(errno, std::system_category());
}
return status;
}std::string const message = "A new message ' with many escaped \" ' quotes \"";
child_process p = popenv("git", {"commit", "-m", message});
// read from p.file; use pclosev() instead of pclose()如果您确实出于某种原因需要一个shell,那么将消息传递到它的argv中并运行git commit -m "$1"。
如果您确实需要让git commit从标准输入读取它的消息,请运行git commit -F -。(可以用任何文件替换-来读取该文件。)
https://stackoverflow.com/questions/43167703
复制相似问题