Home > Software engineering >  Newb Shell - How to get response in a variable
Newb Shell - How to get response in a variable

Time:07-16

Just a quick question to solve an issue I've been facing for days now: how to get an wget json response in a shell variable?

I have so far a wget command like this:

wget "http://IP:PORT/webapi/auth.cgi?account=USER&passwd=PASSWD"

The server reponse is normally something like:

{"data":{"sid":"9O4leaoASc0wgB3J4N01003"},"success":true}

What I'd like to do is to grep the sid value in a variable (as it is used as login ticket), but also the success value in order to ensure that the command has been executed correctly...

I think it is a very easy command to build, but I've never practised wget/http reponse in shell command...

Thanks a lot for your help!

EDIT: Amazing, starting your post with "Hi" or "Hello everybody" is just deleted... This is not about beiing unpolite, sorry for this :)

CodePudding user response:

You can first store the result of wget command in variable and then use it:

VAR=$(wget "http://IP:PORT/webapi/auth.cgi?account=USER&passwd=PASSWD")

and then using jq extract from JSON file:

sid=$(echo $VAR|jq .data.sid)
success=$(echo $VAR|jq .success)

CodePudding user response:

Hello and thanks for your help. I did gave a try to both answers, but I am having the same error message (whatever I do):

--2022-07-16 14:21:38--  http://xxxxxxxx:port/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=3&account=USER&passwd=PWD&session=SurveillanceStation&format=sid
Connecting to 192.168.1.100:5000... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]
auth.cgi?api=SYNO.API.Auth&method=Login&version=3&account=USER&passwd=PASSWD&session=SurveillanceStation&format=sid: Permission denied

Cannot write to `auth.cgi?api=SYNO.API.Auth&method=Login&version=3&account=USER&passwd=PASSWD&session=SurveillanceStation&format=sid' (Permission denied).

The annoying thing: execution the URL from a web browser works just fine... :/

CodePudding user response:

So this can be done using the stream editor or "sed". There is a lot to learn but for this post here is an idea of a code:

sid=$(wget <your url> | sed 's/.*sid":"\(.*\)"},.*/\1/')
success=$(wget <your url> | sed 's/.*success":\(.*\)}/\1/')

This will create 2 variables $sid and $success.

you can learn more about sed in depth here.

Hope this helped!

  • Related