本文介绍了如何在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}
我想像这样运行它:
sh connect.sh server1
无法弄清楚如何使用参数名称作为变量.阵列在我的Ubuntu上也不起作用.
Can't figure out how to use the parameter's name as a variable. Arrays do not work on my Ubuntu too.
推荐答案
使用shell间接寻址,如下所示:
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}
这篇关于如何在bash脚本中将参数/参数名称用作变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!