Art F Art F - 2 months ago 17
Bash Question

Store result of an operations in a variable in bash

I have a command in bash that returns the locale of an IP address stored in variable

$line
. The command looks something like this:

geoiplookup -f GeoIP.dat "$line" >> resultFile


which will return a result such as "New York, NY".

Now I want to concatenate the Ip address to the result so it looks something like this:

"215.216.217.218, New York, NY"

So something like:

$line +", "+ (geoiplookup -f GeoIP.dat "$line") >>resultFile


Can anyone give me the correct syntax to do this?

Answer

How about

echo "$line, $(geoiplookup -f GeoIP.dat "$line")" >> resultFile

This relies on the backtick operator of bash $(...) which executes a command and captures its output. So in the above line, bash will execute geoiplookup -f GeoIP.dat "$line" and put its output in place of the $(...) part.