gpt4 book ai didi

linux - 在shell脚本中的远程ssh命令中传递变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:46 24 4
gpt4 key购买 nike

目前我有这个文件...

#!/usr/bin/env bash

DIRECTORY=$1

ssh root@example.com "$( cat <<'EOT'
cd /web/$DIRECTORY || exit
pwd
unset GIT_DIR
git log --oneline -n 10 --decorate
git branch
EOT
)";

为什么 pwd 只打印出“/web/”?它实际上似乎并没有使用我的变量。然后所有的 git 命令都会抛出关于在 web 目录中的错误。

如果我在 ssh-ing 之前让它回显 $DIRECTORY,它会回显我的变量,但拒绝将它传递给 ssh 命令?

最佳答案

发生这种情况是因为您引用了此处的文档定界符。这是 POSIX :

If any character in word is quoted, the delimiter is formed by performing quote removal on word, and the here-document lines will not be expanded. Otherwise, the delimiter is the word itself.

下面是一个例子:

#!/bin/bash
var=42

cat << 'end'
With quotes: $var and \$var
end

cat << end
Without quotes: $var and \$var
end

执行时:

With quotes: $var and \$var
Without quotes: 42 and $var

关于linux - 在shell脚本中的远程ssh命令中传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com