0

I'm running some code on a remote server over ssh but when i try to execute code to save to the variable 'APP' it will run before mounting the file and also do that on the local machine instead of the remote. What am i doing wrong?

ssh $TARGET_USER@$TARGET_IP << EOF
if [ ${PACKAGE: -4} == ".dmg" ]; then
    hdiutil attach -mountpoint $MOUNTPOINT $FILE_STORE$PACKAGE
    APP=`sudo find $MOUNTPOINT -maxdepth 2 -name \*.app | wc -l | tr -d ' '`
fi
EOF

Here is a cutdown version of my code, i want the variable APP to contain the number of lines 0 or 1 or more.

3 Answers 3

2

I don't understand completely what you want but most if not all of your problems are due to the << EOF part:

You local shell does certain expansion of the stuff before the result is sent to the remote end where it is executed. This affects both the $VAR stuff and the backtick stuff.

if you use << 'EOF' instead, then no local replacement takes place.

If - on the other hand - you want replacement of the variables bot not of the backticks then use this:

... << EOF
...
APP=\$(sudo ...)
EOF
Sign up to request clarification or add additional context in comments.

Comments

1

The shell is executing the command in the backticks before sending it to your ssh command.

2 Comments

Yes but how do i stop that. I want to run the command in the back ticks after and save the output in the variable.
It may be a race condition, whereas hdiutil is forking background processes which don't finish before the sudo command runs. You can try putting a sleep 5 between the commands and see if that helps, if only for testing purposes. However, I still think the shell is interpreting the backticks before anything else because it's in a HERE document, so it has to run that command before sending the output to ssh
1

Quoting the heredoc label will prevent expansion.

Here is simpler form that shows the difference:

cat << EOF
foo=`echo foo`
EOF

yields

foo=foo

vs

cat << "EOF"
foo=`echo foo`
EOF

yields

foo=`echo foo`

There are lots of examples here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.