【问题标题】:Passing variables in remote ssh command in shell script在 shell 脚本中的远程 ssh 命令中传递变量
【发布时间】:2017-06-29 16:56:50
【问题描述】:

目前我有这个文件...

#!/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 命令?

【问题讨论】:

    标签: linux shell ssh


    【解决方案1】:

    发生这种情况是因为您引用了 here doc 分隔符。这里是POSIX

    如果word中的任何字符被引用,则通过对word进行引号去除形成分隔符,并且here-document行不会被扩展。否则,分隔符就是单词本身。

    这是一个例子:

    #!/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
    

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 2015-05-13
      • 2011-02-03
      • 2012-07-18
      • 2012-10-31
      • 1970-01-01
      • 2012-10-21
      • 2011-10-08
      • 1970-01-01
      相关资源
      最近更新 更多