在为for循环| bash中为变量赋值时发出问题

时间:2017-08-24 18:25:11

标签: linux bash shell variables for-loop

我在下面的代码中找不到命令错误:

Network network;  // filled in from ConnectivityManager.NetworkCallback
OkHttpClient client = new OkHttpClient.Builder()
        .socketFactory(network.getSocketFactory())
        .build();

调试输出是:

./test.sh
++ cat output
+for i in '`cat  output`'
++ /usr/efm-2.0/bin/efm cluster-status abc
++ grep Master
++ head -1
++ awk -F ' ' '{print$2}'
+eval 'MASTER_abc = 10.x.x.x'
++ MASTER_abc = 10.x.x.x
**./test.sh: line 5: MASTER_abc: command not found**
+echo -e abc
abc

2 个答案:

答案 0 :(得分:2)

=周围有空格...如果您尝试运行eval "i = 1",它会尝试运行命令i,参数=1而不是将i设置为1

答案 1 :(得分:1)

强烈建议您使用bash关联数组而不是动态变量名:

#!/bin/bash
#set -x
declare -A master
while IFS= read -r line; do
    master["$line"]=$( /usr/efm-2.0/bin/efm cluster-status "$line" 2>/dev/null |awk '/Master/ {print $2; exit}' )
done < output.file

for line in "${!master[@]}"; do
    printf "%s\t%s\n" "$line" "${master[$line]}"
done