3

Am having difficulty checking if the contents of a variable contains a certain value or not e.g "Device_info"

The main code

if [ "${NUMBERRESULTS}" -eq 10 ] 
then
    echo "Success"
else
    echo "Failed"
fi

The above query/script in addition to the variable initialisation produced 14 results when i run it (devices.sh) which was accurate but in this case I want to verify if the $NUMBERRESULTS variable or the result contains the device_info value or not. see below

Here is the code I am writing

if [[ $NUMBERRESULTS =~ .*device_info.* ]] - i tried using the =~ operator
then
    echo "Success a device is present";
else
    echo "Failed no device is present"
fi

See the values/fields i need to verify if they are present or not in the $NUMBERRESULTS variable results/contents.

"device_info": {      i need to check if this field/value is present or not.
    "connected_count": 36,
    "current_config_id": 1618,
    "default_config_id": 1618,
    "first_connected": 1454576905,
    "last_connected": 1454931872,
    "registered": 1454576905,
    "ip_address": "90.152.29.158",
    "model_number": "GT-I9505",
    "serial_number": "restful_api_device",
    "mac_address": "00:00:00:00:00:00",
    "smartcard": "unknown",
    "hardware_version": "0",
    "software_version": "83886336",
    "manufacturer": "SAMSUNG"

thanks very much

9
  • You expect a variable whose name says it contains a number, and which you're already testing as if it does contain only a number, to instead contain a bunch of JSON text? That's... very misleading naming, at best. Commented Feb 10, 2016 at 17:48
  • 2
    Also, for extracting content from JSON input in bash, there are very good dedicated tools such as jq available, it's not good form to try to roll your own. Commented Feb 10, 2016 at 17:49
  • Anyhow: Before this can be answered, you should create a reproducer: Code someone else can copy-and-paste to run that will produce exactly the same behavior you're seeing now. Do that, and describe what the behavior you want is, and this will actually be answerable. Right now, your question is internally inconsistent (we don't even know what data type your variable contains -- and it looks like perhaps you don't either), so it's not in a good place to be answered. Commented Feb 10, 2016 at 17:50
  • Are you just trying to check if the${NUMBERRESULTS} variable is equal to "device_info"? if [[ ${NUMBERRESULTS} = "device_info" ]] ; then ; echo "success" ; else ; echo "fail" ; fi Commented Feb 10, 2016 at 18:42
  • OR... if [[ $(echo ${NUMBERRESULTS} | grep -c device) != "0" ]] ; then ; echo "success" ; else ; echo "fail" ; fi This will count how many times "device" is in the ${NUMBERRESULTS} variable, and if it finds the word "device" at all, it will print success. Commented Feb 10, 2016 at 18:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.