The base problem is that the command being sent over ssh
is in double-quotes, so the $( ... )
and $UP
are being expanded by the local shell before the command is passed to the ssh
command and thence to the remote shell.
Also, quotes don't nest, so the double-quotes in the command string don't do what you want -- the first of each pair is treated as a close-quote (matching whichever was before it), the section that's supposed to be quoted is then not in quotes at all, and the next double-quote starts a new quoted section. Since those are quotes around sections of the argument, the local shell removes them from the argument before passing it to ssh
.
Between those two things, and assuming that ntpd
is not running on the local computer, here's what actually gets passed to the remote computer as a command:
UP= 0;
if [ -ne 1 ];
then
echo NTP is down.;
sudo service ntpd start
else
echo NTP Service is running.;
fi
The [ -ne ]
expression is missing its left operand (remember, the quotes got removed), so [
complains about that. I'm not sure why it thinks that's on line 1, as it looks like line 2 to me.
Solution 1: Use single-quotes around the whole command. Since it doesn't have any single-quotes in it nesting isn't an issue, and single-quotes suppress expansion of everything, so the various $
expansions happen on the remote system.
Solution 2: Pass the commands as a (quoted) here-document instead of an argument (BTW, I also double-quoted $EMAILMESSAGE
on general principles, and removed semicolons from the ends of lines where they're not needed):
ssh $USR@$host >> "$EMAILMESSAGE" <<'EOF'
UP=$(ps -ef | grep -v grep | grep ntpd | wc -l);
if [ "$UP" -ne 1 ]
then
echo "NTP is down."
sudo service ntpd start
else
echo "NTP Service is running."
fi
EOF
Solution 3: Skip the variable, and just use grep -q
directly as the if
test, and either escape the internal double-quotes or switch to single-quotes:
ssh $USR@$host "if ps -ef | grep -v grep | grep -q ntpd
then
echo \"NTP is down.\"
sudo service ntpd start
else
echo \"NTP Service is running.\"
fi" >> "$EMAILMESSAGE"
ssh $USR@$host "UP=$(ps -ef | grep -v grep | grep ntpd | wc -l)";
"
appears to be after thefi
a few lines down - presumably because the intention is to run the whole thing on the remote host (it wouldn't make sense to assignUP
on the remote host then try to test it on the local host). Perhaps the outer"
just need to be changed to'
?