0

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

appreciate if you can help

1
  • 1
    Probably try shellcheck.net before asking for human assistance. Your script contains several common beginner errors. Commented Oct 9, 2022 at 11:22

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.