BASH
I'm writing a script to check services on a selection of hosts for a selection of users. The selected users are stored in an array. The script connects via ssh to each selected host and would go looping through the array logging in to each selected user. However the script fails to read the index of array given by for cycle during ssh - it takes only the 1st (0) index of the array. I've tried almost every possible quoting, escaping, etc... When i escape the $j variable in the echo or "checking" step, i get a syntax error: operand expected (error token is “$j”)
error. Any ideas on how to make it work? Is it even possible?
usr1=("user1" "user2")
function tusr {
declare -n tmpp="$1";
echo "${tmpp[$j]}"
}
function testchk {
echo "Logging in as $myuser to $1"
ssh -tq $myuser@$1.bar.com "
for j in ${!usr1[@]}; do
echo \$j
echo ${usr1[$j]}
echo "Checking $(tusr usr1 "\$j"):"
done
"
}
srv="foo"
testchk "$srv"
When echoing the escaped $j, it prints out the correct value.
My output:
0
user1
Checking user1:
1
user1
Checking user1:
Expected output:
0
user1
Checking user1:
1
user2
Checking user2:
CodePudding user response:
The remote shell doesn't know of your local variables or functions, so you'll need to pass their declarations.
ssh -tq $myuser@$1.bar.com "
$(declare -p usr1)
$(declare -f tusr)
for j in \${!usr1[@]}
do
echo \"\$j\"
echo \"\${usr1[\$j]}\"
echo \"Checking \$(tusr usr1 \$j):\"
done
"
But what you're trying to do is a real mix of things and it's confusing. Are you trying to make the remote user to execute the function tusr
locally ??