引用以将变量/代码传递给每个正在运行的 ssh 的 git 子模块



我需要在已经双引号的字符串中使用双引号。我也尝试使用 $(...(,并检查了多个有点相关的堆栈帖子 [1]、[2],但没有一个解决了这个问题。这些是我尝试执行的命令 -

git submodule foreach 'ssh "${instance_ipaddr}" "[ -d ${REMOTE_GIT_REPO_DIR}/${path}/.git ] || git init ${REMOTE_GIT_REPO_DIR}/${path}"'
git submodule foreach 'submodule_stash_commit=$(git rev-parse HEAD); git push -uf "ssh://${instance_ipaddr}/${REMOTE_GIT_REPO_DIR}/${path}" "${submodule_stash_commit}:refs/heads/remote-push"'
git submodule foreach 'submodule_stash_commit=$(git rev-parse HEAD); ssh "${instance_ipaddr}" "cd ${REMOTE_GIT_REPO_DIR}/${path} && git checkout ${submodule_stash_commit}"'

在这些命令中,我想替换git submodule foreach命令后面的单引号。

与其试图自己弄清楚如何嵌套引号,不如让 shell 为您完成。考虑:

# put the code we want to run remotely in a function
cmd1_remote_part() { [ -d "$1/.git" ] || git init "$1"; }
cmd1() {
# create a single string with the remote argument(s) we want to pass w/ eval-safe quoting
printf -v args_q '%q ' "${REMOTE_GIT_REPO_DIR}/${path}"
# pass to the remote shell (1) the function definition; (2) a function invocation;
# ...(3) the above argument list.
ssh "${instance_ipaddr}" "$(declare -f cmd1_remote_part); cmd1_remote_part $args_q"
}
cmd2() {
submodule_stash_commit=$(git rev-parse HEAD)
git push -uf "ssh://${instance_ipaddr}/${REMOTE_GIT_REPO_DIR}/${path}" 
"${submodule_stash_commit}:refs/heads/remote-push"
}
cmd3() {
submodule_stash_commit=$(git rev-parse HEAD)
# substituting paths into remote ssh commands introduces security risks absent eval-safe
# ...quoting, as done with printf %q.
printf -v remote_cmd_q 'cd %q && git checkout %q' 
"${REMOTE_GIT_REPO_DIR}/${path}" "${submodule_stash_commit}"
ssh "${instance_ipaddr}" "$remote_cmd_q"
}
git submodule foreach "$(declare -f cmd1 cmd1_remote_part); cmd1"
git submodule foreach "$(declare -f cmd2); cmd2"
git submodule foreach "$(declare -f cmd3); cmd3"

请注意,所有这些函数的主体的编写方式与您为本地 shell 编写它们的方式完全相同; 然后,declare -f发出一个可以远程扩展的函数声明。

最新更新