0

我需要从 ec2din webservice 的输出中存储 ec2url、大小和其他一些特定参数。

目前我正在这样做

 ec2url=`ec2din ${instance[n]} --region $i | grep INSTANCE | awk '{print($4)}'`
 size=$(ec2din ${instance[n]}  --region $i | grep INSTANCE | awk '{print($9)}')
 comment=$(ec2din ${instance[n]} --region $i | grep TAG | awk '{print($5)($6)($7($8)}';)

但是在这个过程中它会运行 3 次 web 服务,这会影响脚本的执行速度

我能想到的一种方法是将输出存储在一个文件中并在 for 循环中从那里读取它

但是,让我知道是否有任何其他最佳方法可以实现这一目标。

4

1 回答 1

1

Store the output first on a variable then reuse it on other commands:

output=$(ec2din "${instance[n]}" --region "$i")
ec2url=$(echo "$output" | grep INSTANCE | awk '{print($4)}')
size=$(echo "$output" | grep INSTANCE | awk '{print($9)}')
comment=$(echo "$output" | grep TAG | awk '{print($5)($6)($7($8)}')

And you could actually just exclude grep and just use awk:

output=$(ec2din "${instance[n]}" --region "$i")
ec2url=$(echo "$output" | awk '/INSTANCE/{print($4)}')
size=$(echo "$output" | awk '/INSTANCE/{print($9)}')
comment=$(echo "$output" | awk '/TAG/{print($5)($6)($7($8)}')

Another way is to use here strings instead of using echo:

output=$(ec2din "${instance[n]}" --region "$i")
ec2url=$(awk '/INSTANCE/{print($4)}' <<< "$output")
size=$(awk '/INSTANCE/{print($9)}' <<< "$output")
comment=$(awk '/TAG/{print($5)($6)($7($8)}' <<< "$output")

If instances of INSTANCE is expected to be one line only you could improve it further with read:

output=$(ec2din "${instance[n]}" --region "$i")
IFS=$'\n' read -rd '' ec2url size < <(awk '/INSTANCE/{print($4 "\n" $9)}' <<< "$output")
comment=$(awk '/TAG/{print($5)($6)($7($8)}' <<< "$output")

And if INSTANCE is expect to be seen before TAG and that both could always exist and not only one of them then you could put everything as one line:

IFS=$'\n' read -rd '' ec2url size comment < <(ec2din "${instance[n]}" --region "$i" | awk '/INSTANCE/{print($4 "\n" $9)};/TAG/{print($5)($6)($7($8)}')
于 2013-08-13T12:53:56.193 回答