为什么此Shell脚本仅对一个实例有效,而对另一个实例无效? [英] Why does this shell script work for one instance and not the other?
问题描述
我需要对以下代码进行一些解释,因为它们是相同的概念,但工作原理不同.因此,我正在尝试执行以下操作:
I'm in need of some explanation of the following code, because they are the same concepts but not working the same. So, I'm trying to do the following:
#!/bin/sh
ssh -T username@host << EOF
relative="$HOME/Documents"
command=$(find \$relative -name GitHub)
command2=$(echo \$relative)
echo "HERE: \$command"
echo "HERE: \$command2"
EOF
这是我得到的输出:
find: ‘$relative’: No such file or directory
HERE:
HERE: /home/username/Documents
我尝试了以下操作:
"\$relative"
'\$relative'
"\${relative}"
"\$(relative)"
推荐答案
您大部分步骤都做对了,但是忘记了这里文档 $(..)
中的命令替换构造..不这样做将使命令在本地外壳而不是远程主机中扩展.
You did the most parts right, but forgot to escape the command-substitution construct in the here-doc $(..)
. Not doing it will make the command expand in the local shell and not in the remote host.
在运行 find
命令时,转义的 \ $ relative
会将文字字符串传递给它不理解的 find
命令,即在本地计算机上发生以下情况
Also while running the find
command an escaped \$relative
will pass the literal string to the find
command which it does not understand, i.e. the following happens on the local machine
find \$relative
# ^^^^ since $relative won't expand, find throws an error
因此,您需要转义整个命令替换结构,以将整个here-doc扩展移动到远程主机中.
So you need to escape the whole command-substitution constructs, to move the whole here-doc expansion in the remote host.
ssh -T username@host << EOF
relative="\$HOME/Documents"
command=\$(find "\$relative" -name GitHub)
command2=\$(echo "\$relative")
echo "HERE: \$command"
echo "HERE: \$command2"
EOF
或者完全使用heredocs的替代形式,允许您不解释heredoc文本中的变量.只需将定界标识符引用为'EOF'
Or altogether use an alternate form of heredocs that allows you to not interpret variables in the heredoc text. Simply quote the delimiting identifier as 'EOF'
ssh -T username@host <<'EOF'
relative="$HOME/Documents"
command=$(find "$relative" -name GitHub)
command2=$(echo "$relative")
echo "HERE: $command"
echo "HERE: $command2"
EOF
这篇关于为什么此Shell脚本仅对一个实例有效,而对另一个实例无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!