Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an argument/parameter name as a variable in a bash script

Tags:

bash

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.

like image 856
Yasen Avatar asked Apr 06 '26 07:04

Yasen


1 Answers

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}
like image 177
anubhava Avatar answered Apr 10 '26 12:04

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!