Reputation: 29
Inside the remote server i have a condition statement.If that condition passes status value should be set as success.
But here i am always getting Failure response while i print status variable
status='Success';
status='Success';
# !/bin/bash
declare -a server_PP=('XXXXX' 'YYYYYYY' );
declare -A results_map;
function process(){
serverList=$1[@];
servers=("${!serverList}");
status='Failure';
for serverName in "${servers[@]}"
do
ssh $serverName << EOF
if [ -f /app/Release/abc.war ]; then
echo "available - success"
status='Success';
fi
echo "***********status-inside******$status"
exit
EOF
echo "***********status-outside******$status"
results_map+=([$serverName]=$status);
done
}
process 'server_PP'
for i in "${!results_map[@]}"
do
echo "key :" $i
echo "value:" ${results_map[$i]}
done
Status variable should set as success when that condition get satisfied.
Upvotes: 2
Views: 528
Reputation: 9855
As written in pcarter's comment, the variables on both systems are independent from each other and don't get passed via ssh
. Instead of setting a variable (or printing and reading the value as proposed in the comment, which is a working solution) you can use the exit code which gets passed automatically by ssh
.
The following script is close to the original. For further improvements see below.
# !/bin/bash
declare -a server_PP=('XXXXX' 'YYYYYYY' );
declare -A results_map;
function process(){
serverList=$1[@];
servers=("${!serverList}");
status='Failure';
for serverName in "${servers[@]}"
do
if ssh $serverName << EOF
if [ -f /app/Release/abc.war ]; then
echo "available - success"
exit 0;
fi
echo "error"
exit 1
EOF
then
status='Success'
else
status='Failure'
fi
echo "***********status-outside******$status"
results_map+=([$serverName]=$status);
done
}
process 'server_PP'
for i in "${!results_map[@]}"
do
echo "key :" $i
echo "value:" ${results_map[$i]}
done
As you no longer need the variable assignments you can even omit the if ...
and exit
in the remote commands.
if ssh $serverName << EOF
[ -f /app/Release/abc.war ]
EOF
then
...
Your approach of using a heredoc as
ssh hostname <<EOF
# commands ...
EOF
has the disadvantage that you run an interactive shell on the remote system, which may print some system information or welcome message before executing your commands. You can further simplify the script (and removing the welcome message) by specifying the command or a script as command line arguments for ssh
.
if ssh $serverName [ -f /app/Release/abc.war ]
then
...
If your command sequence is longer you can create a script on the remote system and run this script in the same way as ssh hostname scriptname
. You could also create the script on the remote system using ssh
or scp
.
Upvotes: 1