0

I am running a for loop that calls in a variable from another file:

hostnames.txt

The variables in that file look like this:

export HOSTNAME_0=<hostname>
export HOSTNAME_1=<hostname>
export HOSTNAME_2=<hostname>

I am trying use them inside a for loop like this:

. hostnames.txt
for f in {0..10}; do
ssh $HOSTNAME_'{$f}'
if [$? !=0]; then
   echo "Unable to SSH to server $HOSTNAME_'{$f}'"
   exit 1
fi

However its not reading the value correctly, and I'm not sure what I'm missing. Would love any help.

1
  • Check your spacing inside the [ ], or maybe use (( )) Commented Apr 14, 2017 at 15:25

2 Answers 2

3

You need to build your variable name and access it with ${!var}, e.g.:

. hostnames.txt
for f in {0..10}; do
  hostnamevar=HOSTNAME_${f}
  ssh ${!hostnamevar}
  if [ $? -ne 0 ]; then
    echo "Unable to SSH to server ${!hostnamevar}"
    exit 1
  fi
done
Sign up to request clarification or add additional context in comments.

4 Comments

You need spaces in the if test expression: if [ $? != 0 ]; then.
@GordonDavisson I was merely copying his code which wasn’t relevant IMO. Anyways I’ve edited the answer so as to fix the rest of his code too.
Thanks that worked. I have an additional question though, I have additional commands I want to execute on the remote server after I've logged in and now none of them are running. Any idea how do actually get them to run?
@user2019182 Since this looks like a different issue, please open another thread.
1

When you don't have other vars starting with "HOSTNAME", you can use

    . hostnames.txt
    for host in $(set | sed -n '/^HOSTNAME*=/ s/[^=]*=//p') ; do
       ssh "${host}"
       # or, for calling 2 commands:
       # ssh "${host}" "echo 1 2 3; echo 4"
       if [ $? -ne 0 ]; then
          echo "Unable to SSH to server ${host}"
          exit 1
       fi
    done

Comments

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.