Nie*_*ng 26 bash shell arguments function heredoc
是否可以将此文档作为bash函数参数传递,并且在函数中将参数保留为多行变量?
以下内容:
function printArgs {
echo arg1="$1"
echo -n arg2=
cat <<EOF
$2
EOF
}
printArgs 17 <<EOF
18
19
EOF
Run Code Online (Sandbox Code Playgroud)
或者可能:
printArgs 17 $(cat <<EOF
18
19
EOF)
Run Code Online (Sandbox Code Playgroud)
我有一个here文档,我想将ssh作为执行命令提供给ssh会话,并从bash函数调用ssh会话.
Rob*_*kop 15
可行的方法是:
printArgs 17 "$(cat <<EOF
18
19
EOF
)"
Run Code Online (Sandbox Code Playgroud)
但是你为什么要使用heredoc呢?heredoc被视为参数中的文件,因此您必须(ab)使用cat来获取文件的内容,为什么不执行以下操作:
print Args 17 "18
19"
Run Code Online (Sandbox Code Playgroud)
请记住,最好在你想要ssh的机器上创建一个脚本并运行然后尝试一些这样的hack,因为bash仍会在你的多行参数中扩展变量等.
如果你没有使用能够吸收标准输入的东西,那么你将不得不提供能够做到这一点的东西:
$ foo () { while read -r line; do var+=$line; done; }
$ foo <<EOF
a
b
c
EOF
Run Code Online (Sandbox Code Playgroud)
基于 Ned 的回答,我的解决方案允许函数将其输入作为参数列表或 heredoc。
printArgs() (
[[ $# -gt 0 ]] && exec <<< $*
ssh -T remotehost
)
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做
printArgs uname
Run Code Online (Sandbox Code Playgroud)
或这个
printArgs << EOF
uname
uptime
EOF
Run Code Online (Sandbox Code Playgroud)
因此,您可以对单个命令使用第一种形式,对多个命令使用长形式。