How to insert a query value into a variable in the Shell Script?

Asked

Viewed 415 times

1

I have a JSON in an archive nomes.txt.

the JSON is :

{"p": { "nome": ["josé","Maria", "carlos","Artur"] }}

I want to play the value of his query in a variable.

Show result works fine :

#!/bin/bash

ns=`cat nomes.txt`

echo $ns

for ((i=0; i<=4; i++))
do
        echo $ns | jq -r ".p | .nome[$i]"
done

But when I try to do something more elaborate I can’t.

I want to play the value of JSON captured in variable but will not .

#!/bin/bash

ns=`cat nomes.txt`

echo $ns

for ((i=0; i<=4; i++))
do
        aux=$ns | jq -r ".p | .nome[$i]"
        echo "O nome $i é $aux"
done

The value of $aux is void.

How can I transfer the value to the variable aux ?

1 answer

0

I ran a test and I believe you can solve it using the command encompassed by $()

Thus:

  aux=$($ns | jq -r ".p | .nome[$i]")

The test I did here was using the command $ls, thus:

ls='ls'
result=$($ls -la)
echo $result

In my result, it saved the directory listing in the variable result.

According to the reply of SOEN, $() means "Run the command and put your output here"

I even asked a question to help with that question:

What is the $() dollar sign followed by parentheses in BASH for?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.