Search code examples
bashshellif-statementdebianraspbian

If statement doesn't execute argument


GNU nano 2.7.4     File: /home/pi/initDisplay/initDisplay.sh               
#!/usr/bin/env bash

#HDMI connection?

rm -f hdmi.name
tvservice -n 2>hdmi.name
HDMI_NAME=`cat hdmi.name`                                                    
echo $HDMI_NAME
if [ "$HDMI_NAME" == "[E] No device present" ]; then
    LCD_ON=`cat /boot/config.txt | grep "#CONFIGURAZIONEHDMI"`
    echo $LCD_ON
    if [ "$LCD_ON" == "#CONFIGURAZIONEHDMI" ]; then
        echo "reboot con la configurazione LCD"
        sudo rm -f /boot/config.txt
        sudo cp /boot/config_lcd.txt /boot/config.txt
        sleep 2
        sudo  reboot -n
    fi                                 
else
    HDMI_ON=`cat /boot/config.txt | grep "#CONFIGURAZIONELCD"`
    echo $HDMI_ON
    if [ $HDMI_ON == "#CONFIGURAZIONELCD" ]; then
        echo "reboot con la configurazione HDMI"
        sudo rm -f /boot/config.txt
        sudo cp /boot/config_hdmi.txt /boot/config.txt
        sleep 2
        sudo reboot -n
    fi
fi

Doesn't start the arg of if statement with $LCD_ON. When I try to execute it, it doesn't return what I expect. Now it returns:

[E] no device detected
#CONFIGURAZIONEHDMI

but it doesn't start to replace file and reboot.

P.S.: The user and the file have privileges to do it And I already set chmod 777 the file


Solution

  • There might be more on the line that matches, such as extra whitespace, so the equality test doesn't match exactly.

    If you want to test whether a matching line exists in a file, you can just test the exit status of grep, rather than storing the output in a variable.

    if grep -q "#CONFIGURAZIONEHDMI" /boot/config.txt; then
        echo "reboot con la configurazione LCD"
        sudo rm -f /boot/config.txt
        sudo cp /boot/config_lcd.txt /boot/config.txt
        sleep 2
        sudo  reboot -n
    fi  
    

    The -q option tells grep not to print the matching line, it just sets its exit status.