Reputation: 1385
I'm making a bash script that exits if the remote server has a specific file and specific contents.
I check the file with the code below:
ssh $DEPLOY_HOST 'VAR=false
if [ -f /filename ]; then
. /filename
REMOTEID=$ID
if [ "$REMOTEID" == "something" ]; then
VAR=true
fi
else
echo "Missing /filename"
fi
if [ "$VAR" == false ]; then
exit 1
fi
'
But that exit command doesn't work for local server, so the afterward code is executed, which I don't expect.
I think I have to get the result variable(VAR) from the remote server so that the local server can decide whether to exit or not with the variable.
How can I solve this?
Thanks :)
Upvotes: 1
Views: 604
Reputation: 2610
Try this:
ssh $REMOTE 'test -e file' && exit
where file
is the name of the file on the REMOTE server that you want to check for existence.
The exit code from the test
command on the REMOTE server will be passed through ssh
's exit code into your local shell and be used with the &&
operator.
If you need to return the string value of a variable, you could use this pattern:
VAR=$(ssh $REMOTE '
{
some command
some other command
...
# all of the stdout from these commands will be discarded
} > /dev/null
echo $VAR # the stdout from here will be returned as stdout from ssh
')
Let's break this down:
{}
block groups all commands where we want to discard stdout.''
single quotes capture all of the commands to run on the REMOTE serverVAR=$(ssh ' ... ')
command will take stdout from the echo $VAR
and place it in the local variable named VAR
.Upvotes: 1