在heredoc部分设置变量 [英] set variable in heredoc section
问题描述
我是一个shell脚本新手,所以我必须做一些愚蠢的事,为什么这项工作不起作用:
I'm a shell script newbie, so I must be doing something stupid, why won't this work:
#!/bin/sh
myFile=$1
while read line
do
ssh $USER@$line <<ENDSSH
ls -d foo* | wc -l
count=`ls -d foo* | wc -l`
echo $count
ENDSSH
done <$myfile
应该打印两行,每行应该具有相同的值...但是它们没有.第一个打印语句[ls -d foo *的结果| wc -l]的值正确,第二个打印语句不正确,它始终打印为空白.我需要做一些特殊的事情来将值分配给$ count吗?
Two lines should be printed, and each should have the same value... but they don't. The first print statement [the result of ls -d foo* | wc -l] has the correct value, the second print statement is incorrect, it always prints blank. Do I need to do something special to assign the value to $count?
我在做什么错了?
谢谢
推荐答案
#!/bin/sh
while read line; do
echo Begin $line
ssh $USER@$line << \ENDSSH
ls -d foo* | wc -l
count=`ls -d foo* | wc -l`
echo $count
ENDSSH
done < $1
脚本的唯一问题是,当未引用heredoc令牌时,shell会进行变量扩展,因此$count
在您的远程命令交付之前已由您的本地shell进行了扩展...
The only problem with your script was that when the heredoc token is not quoted, the shell does variable expansion, so $count
was being expanded by your local shell before the remote commands were shipped off...
这篇关于在heredoc部分设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!