Ruchir Bharadwaj
Ruchir Bharadwaj

Reputation: 1272

how to store specific output of ec2din in separate variables

I have a need where I want to store ec2url, size and some other specific parameter from the output of ec2din webservice.

Currently I am doing this by

 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)}';)

However in this process it runs the webservice 3 times which affect execution speed of script

One way I can think of is to store the output in a file and read it from there in for loop

However let me know if there is any other best way to achieve this.

Upvotes: 0

Views: 142

Answers (1)

konsolebox
konsolebox

Reputation: 75548

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)}')

Upvotes: 1

Related Questions