0

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:
0

1 Answer 1

1

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 ??

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. I created function tusr to print out or return the n-th user of an array. I log in via ssh to remote host under my user. Under this connection, i'd like to cycle through the usr1 array and log in as each user in array and under this user execute further commands. As far as i know, the cycling works as expected, the issue is that the tusr function, or this - echo \"\${usr1[\$j]}\" doesn't see the value of $j.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.