使用引用与未引用 Heredocs 的全局变量

Global Variables using Quoted vs. Unquoted Heredocs

我很好奇我能不能把我的蛋糕也吃掉。我正在编写一个脚本,需要在远程服务器上找到具有最新日期的目录。然后我需要构建该路径,以便我可以在服务器上找到特定的 .csv 文件。

该脚本接受一个名为 folder 的输入,它需要附加到路径的末尾。我注意到我可以将文件夹传递到 heredoc 并扩展它,但是我失去了我需要做的 awk 扩展。这是一个例子:

folder='HBEP'
ssh $server /bin/bash << EOF
ls -t /projects/bison/git |
head -1 |
awk -v folder=$folder '{print "projects/bison/git/""/assessment/LWR/validation/"folder}'
EOF

这会产生接近但错误的输出:

# output:
/projects/bison/git//assessment/LWR/validation/HBEB

# should be:
/projects/bison/git/bison_20190827/LWR/validation/HBEP

现在,当我引用 EOF 时,我可以访问管道输入变量但不能访问文件夹变量:

folder='
ssh $server /bin/bash << 'EOF'
ls -t /projects/bison/git |
head -1 |
awk -v folder="$folder" '{print "projects/bison/git/""/assessment/LWR/validation/"folder}'
EOF
# output:
projects/bison/git/bison_20190826/assessment/LWR/validation/

# should be:
projects/bison/git/bison_20190826/assessment/LWR/validation/HBEP

有什么方法可以利用 heredoc 和外部的扩展 shell?

您可以使用不带引号的 heredoc 版本。如果要避免参数扩展,只需在 $ 之前添加 \

例如

folder='HBEP'
ssh $server /bin/bash << EOF
ls -t /projects/bison/git |
head -1 |
awk -v folder=$folder '{print "projects/bison/git/"$1"/assessment/LWR/validation/"folder}'
EOF