Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

bash - set variable in heredoc section

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

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?

What am I doing wrong?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
#!/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

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...