Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a bash shell script that performs a cURL command, and gets the raw output of an array inside the json array.

I can also successfully echo the number of elements in the array

Why can I not assign the amount of elements inside the array to a variable? it is always blank

Bash
#!/bin/sh
output=$(curl --data '{"janus":"list_sessions","transaction":"123","admin_secret":"123"}' -H "Content-Type: application/json" http://127.0.0.1:7088/admin | jq --raw-output '.sessions')

echo $output
realoutput=$(output | jq '. | length')
echo $output | jq '. | length'
echo "OK|janusSessions=$realoutput"


The output of the following code is as follows:

[ 4218550436352653, 5053829616106050 ]
./list_janus_sessions.sh: 5: output: not found
2
OK|janusSessions=


What I have tried:

I have tried also:

Bash
#!/bin/sh
output=$(curl --data '{"janus":"list_sessions","transaction":"123","admin_secret":"janusoverlord"}' -H "Content-Type: application/json" http://127.0.0.1:7088/admin | jq --raw-output '.sessions')

echo $output
realoutput=$output | jq '. | length'
echo $output | jq '. | length'
echo "OK|janusSessions=$realoutput"


Which produces:
[ 4218550436352653, 5053829616106050 ]
2
OK|janusSessions=


As you can see, the variable is always blank but here must be a simple way of doing this yet I cannot see it
Posted
Updated 11-Jan-22 5:07am
v3
Comments
Richard Deeming 11-Jan-22 10:41am    
I'm not familiar with Bash, but aren't you missing a $ from the variable name?
realoutput=$($output | jq '. | length')
mc96 11-Jan-22 11:00am    
bash does not need $ prefix for variable names unless referring to them, or performing linux commands etc; but I do appreciate your assistance

I do not think you need the extra pipe symbol in:
Shell
echo $output | jq '. | length'
                     ^

Try
Shell
echo $output | jq '.length'
 
Share this answer
 
Comments
mc96 11-Jan-22 11:02am    
I need the pipe there, the echo statement is working fine, assigning the statement I am echoing to a variable does not and I am perplexed as to why
Richard MacCutchan 11-Jan-22 11:04am    
Have you tried it without?
SOLVED!

realoutput=$(echo $output | jq '. | length')


echo "OK|janusSessions=$realoutput"

Produces:
OK|janusSessions=2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900