在其他Bash中使用变量 [英] Using Variables inside one another Bash

查看:149
本文介绍了在其他Bash中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  hostnames.txt 

该文件中的变量如下所示:

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

我正在尝试在这样的for循环中使用它们:

 。 {0..10}中的f的hostnames.txt 
;做
ssh $ HOSTNAME _'{$ f}'
如果[$? != 0];那么
echo无法SSH到服务器$ HOSTNAME _'{$ f}'
exit 1
fi

但是它没有正确读取值,我不知道我错过了什么。请求帮助。

解决方案

您需要构建变量名称并使用 $ {! var} ,例如:

 。 {0..10}中的f的hostnames.txt 
; do
hostnamevar = HOSTNAME _ $ {f}
ssh $ {!hostnamevar}
如果[$? -ne 0];然后
echo无法SSH到服务器$ {!hostnamevar}
exit 1
fi
done


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.

解决方案

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

这篇关于在其他Bash中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆