I would like to check a particular line from a remote server. So far, I can check if the file exists or not. But can I index a particular line using tool like jq?

if ssh -q -i $pathToPem $sshUsernameIp [ -f ${remote_serial} ];


            echo "Serial number is found externally"
            serialNumber=$(cat serialNumber.json | jq '.serialNumber')

            if ssh -q -i $pathToPem $sshUsernameIp [ "$serialNumber" == "${remote_serial | jq '.serialNumber'}" ];
                    echo "Serial number is same"
                    echo "Serial number is not same"


Serial number is found externally
./test.sh: line 127: ${remote_serial | jq '.serialNumber'}: bad substitution

How can I pass variable inside {} there? Can I compare these local and remote files without scp ing?


No need to make it complicated. Just grab the JSON off from the remote host and pass it through jq, then do the same locally. Then compare. If the remote file is missing, you'll get an error (which we can throw away), and the serial numbers will compare different (unless the local serial number is also missing).

r_serial=$( ssh -q -i "$pathToPem" "$sshUsernameIp" cat "$remote_serial" 2>/dev/null | jq -r '.serialNumber' )
l_serial=$( jq -r '.serialNumber' serialNumber.json )

if [ "$r_serial" = "$l_serial" ]; then
    echo 'same'
    echo 'different (or missing)'

This is assuming that $remote_serial is the pathname of the JSON document on the remote machine.

Note also the quoting of the variable expansions in the call to ssh.

The actual error you get comes from the fact that

"${remote_serial | jq '.serialNumber'}"

is not a valid variable expansion. You may have wanted to use something like

"$( printf '%s\n' "$remote_serial" | jq '.serialNumber' )"

but that assumes that $remote_serial contains the contents of a JSON document.

  • Thank you. This one makes it look clean as well. – Rakib Fiha Feb 18 at 15:30

Looks like it should be

"$(echo ${remote_serial} | jq '.serialNumber')"

instead of

"${remote_serial | jq '.serialNumber'}"
  • I tried it, seems like I will have difficulty with parsing with this. parse error: Invalid numeric literal at line 2, column 0 bash: line 0: [: sfsdfsdfdfsdfsd: unary operator expected Serial number is not same – Rakib Fiha Feb 18 at 15:38
  • 1
    I see Kusalananda already supplied you with a better solution with proper quoting. My assumption that the ${remote_serial} might not have spaces nor any other problematic characters was probably incorrect. Kusalananda's solution has properly defensive quoting to handle that. – telcoM Feb 18 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.