Issue
I've got a bash script and I'm trying to perform a command based on a JSON response.
I can have back 3 types of response which I store in the content
variable:
1st type (repo doesn't exist):
{
"message": "The repo doesn't exist"
}
2nd type (repo exists but there's no content):
[
{
"name": ".dotfile"
},
{
"name": ".anotherdotfile"
},
{
"name": "README.md"
},
]
3rd type (repo exists and there's a content):
[
{
"name": ".dotfile"
},
{
"name": ".anotherdotfile"
},
{
"name": "README.md"
},
{
"name": "myscript.sh"
},
{
"name": "anotherscript.sh"
},
{
"name": "anotherfile.sh"
},
]
In my script I have loop like this:
#/bin/bash
for repo_name in "${repos_name[@]}"; do
content=$(curl -s http://example.com/$repo_name)
# Here I would like to check if the response is of the 3rd type.
# So, if it's an array with at least 1 object with value's name
# which not start from "." or equal to "README.md".
# In that case I would perform a command
done
Basically, I would like to check if a repo exist and it has some content apart from the dot files and the README.
I tried to use jq
tool but I don't know how to correctly filter the content to perform the check.
How can I achieve that result?
Solution
This will evaluate to false
given your first two inputs, and true
given the third one. use it as condition in a if
or select
expression if your "command" lives inside jq. Otherwise, you could use jq's --exit-status
(or -e
) flag to set its exit status to 1
or 0
, which you can capture and process in the invoking shell either by assigning $?
to a variable, or by directly using the invocation in an if
statement.
any(arrays[]; .name | . == "README.md" or startswith(".") | not)
Answered By - pmf Answer Checked By - Mary Flores (WPSolving Volunteer)