In general there are more appropriate ways of parsing JSON objects, but since in this case the JSON object is very simple you may store curl
's output in a variable (which is possible) and just use AWK:
var="$(curl ipinfo.io/"8.8.8.8" 2>/dev/null)"
<<<"$var" awk -F'"' '$2=="city"{printf("%s, ", $4)}$2=="region"{print $4}'
% var="$(curl ipinfo.io/"8.8.8.8" 2>/dev/null)"
% <<<"$var" awk -F'"' '$2=="city"{printf("%s, ", $4)}$2=="region"{print $4}'
Mountain View, California
However unless you want to use curl
's output multiple times you may just use a pipe:
curl ipinfo.io/"8.8.8.8" 2>/dev/null | awk -F'"' '$2=="city"{printf("%s, ", $4)}$2=="region"{print $4}'
curl ipinfo.io/"8.8.8.8" 2>/dev/null | awk -F'"' '$2=="city"{printf("%s, ", $4)}$2=="region"{print $4}'
Mountain View, California
<<<
is a form of input redirection called "here string"; it redirects the STDIN of a command from the terminal to a string.
What happens here is that $var
is expanded between the double quotes; the STDIN of the AWK command is redirected from the terminal to the expanded string and AWK consequently reads the string as its input file.
Best Answer
Typically this is accomplished with
if
statement andgrep
pipeline. Something likeTrick here, is that
if
statements operate on exit statuses of commands, and the exit status of the whole pipeline is the exit status of the last command. Of coursegrep -q
will not print anything to the screen, but the zero exit status will tell you whether or not the command succeeded (i.e.grep
found desired string in the output) or not if non-zero.A different approach is via
case
statement, and command substitution, which I'd find perhaps more suitable where output is a single-line, and where you want to shoot for script portability between operating systems ( aka POSIX compliance ).Third way, would be via again command-substitution and
test
command for exact match.Or
bash
's extended test[[
for pattern matching:Those can be used within
if
statement, or with conditional operators like&&
, e.g.[ "$(echo test)" = "test" ] && df
.Best approach, I think would be to make it all a function so that you can pass your argument to the desired command, and perhaps reuse it later within
if
orcase
statement. So something like this:Of course, keep in mind these are just slightly verbose, and perhaps unnecessary, but still examples of how it can be done. Adapt to your specific case as necessary. Keep in mind this is not exhaustive information,too.