2

I'm trying to write a script that allows connection to various servers, e.g.

#!/bin/bash
# list of servers
server1=10.10.10.10
server2=20.20.20.20
ssh ${$1}

And I'd like to run it like:

sh connect.sh server1

Can't figure out how to use the parameter's name as a variable. Arrays do not work on my Ubuntu too.

3 Answers 3

8

Use shell indirection like this:

x=5
y=x
echo ${!y}
5

For your script, following works:

#!/bin/bash
# list of servers
server1=10.10.10.10
server2=20.20.20.20

arg1="$1"
ssh ${!arg1}
Sign up to request clarification or add additional context in comments.

6 Comments

+1 Really nice trick though it should be mentioned that this is bash only.
@helpermethod: Thanks and yes this is for BASH since question was tagged as BASH.
Don't run it sh connect.sh server1 use it like bash connect.sh server1
@Lamy It seems you're using sh and not bash.
+1, but if indirect parameter expansion is available, arrays should be as well.
|
1

Easiest way would be to switch on $1:

case "$1" in
  server1) ssh "$server1"
           ;;
  server2) ssh "$server2"
           ;;
  *) ssh "$server1" # when no parameter is passed default to server1
     ;;
esac

Comments

0

Try this:

#!/bin/bash

# list of servers
server1=10.10.10.10
server2=20.20.20.20

if [ "$1" == "server1" ]; then 
    ssh $server1;
elif [ "$1" == "server2" ]; then 
    ssh $server2;
fi

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.