使用带引号和不带引号的Heredocs的全局变量

时间:2019-08-28 19:07:24

标签: bash awk ssh pipe heredoc

我很好奇我是否也可以吃蛋糕。我正在编写一个脚本,该脚本需要在远程服务器上查找具有最新日期的目录。然后,我需要构建该路径,以便可以在服务器上找到特定的.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/"$1"/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/"$1"/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和外部外壳中的扩展?

1 个答案:

答案 0 :(得分:2)

您可以使用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