Pergunta

Alright, I'm admittedly a noob at Bash, and scripting languages in general, and a first time poster, but I've got a question. I am trying to make a C program that outputs (via COMM port) the temperature of the CPU as an integer. To do get this info, I'm calling a bash script from C using a system() call

I am trying to look at the output of the "sensors" command (part of lm-sensors) to ensure sensors are loaded before accessing temperature, so I need to compare the output of "sensors" with the expected output, which starts as "No sensors found!" in the false case. My script however only prints the output of "sensors", while evaluating the conditional as true (it should evaluate as false)

#!/bin/bash

if [[ "$(sensors)" =~ No* ]]
then
        echo "No sensors found"
else
        echo "Sensors Valid"
fi

Any suggestions to A: Fix the conditional and B: keep it from printing the value of "sensors"? Thanks in advance.

Nick

Foi útil?

Solução

Change if [[ "$(sensors)" =~ No* ]] to if [[ "$(sensors 2>&1)" == No* ]]

The sensors writes No sensors found to standard error, not standard output. You can dupe standard error to standard output within the command substitution to get around this. Also as pointed out by that other guy, use glob comparison

Outras dicas

so I need to compare the output of "sensors" with the expected output, which starts as "No sensors found!" in the false case.

So if the user speaks french and sensors outputs "Pas de capteurs trouvés" ("No sensors found"), do you consider that a true case?

What if sensors is not installed, and prints "bash: sensors: command not found". Do you also consider this a true case?

The correct way of doing this is checking the command's exit status:

if sensors > /dev/null 2>&1
then
  echo "Sensors valid"
else
  echo "sensors failed, due to missing sensors, not being installed or such"
fi
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top