Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error : numeric argument required while executing jq command

Hi I am having a small shell script . however when i run the script it gives the error

sample.sh: line 5: return: null: numeric argument required

The following is my script

#!/bin/bash

function getHeader() {

  return $(jq '."$1"' <<< $2)


}


RESPONSE='{"content-length":"2","address":"10.244.3.1:37930","path":"/hello-world"}'

echo $RESPONSE | jq '.'

x_header=$(getHeader  "content-length" $RESPONSE )

I am also using jq library to handle the json data. In the above example i want the content-length value in the x_header variable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

appreciate if you can help

>Solution :

Unlike in various other languages, in the shell, return isn’t used to return a value but a status. So return can only return numerical values. See help return:

$ help return
return: return [n]
    Return from a shell function.
    
    Causes a function or sourced script to exit with the return value
    specified by N.  If N is omitted, the return status is that of the
    last command executed within the function or script.
    
    Exit Status:
    Returns N, or failure if the shell is not executing a function or script.

If you want to return a string, you need to print it. Or, if its the output of a command, just run the command. You should also quote all variables and avoid using CAPS for your shell variables since, by convention, global environment variables are in caps and this can lead to naming collisions and hard to debug bugs. So, try something like this:

#!/bin/bash

function getHeader() {
  jq ".\"$1\"" <<< "$2"
}

response='{"content-length":"2","address":"10.244.3.1:37930","path":"/hello-world"}'

printf '%s\n' "$response" | jq '.'

x_header=$(getHeader  "content-length" "$response" )

Also see Why is printf better than echo?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading