Search code examples
shellraspberry-pishraspbian

Troubleshooting a script for my RPI to toggle displays


So I have a Quimat LCD attached to my gpio.

included is a script which runs to switch to the display (LCD35-show), and another to switch back to the HDMI port (LCD-hdmi). This causes a reboot when done so any variable changes have to happen prior to this.

as this is for my mother who is afraid of touching command prompt, I am trying to set up a single icon to use to switch between video sources.

I am a novice at coding, most of my experience from dabbling in BASIC, and have spent a couple days searching and trying to set this up, but apparently am failing at how to search properly as I couldn't get it functioning.

What I have done so far is this:

Created text file state.txt to hold a variable stating what mode the device is in (HDMI or LCD)

My attempt was to read the variable, then use if then statement to determine which file to run, change the variable then run the file.

This is the code I ended up with.

!/bin/bash
read var < state.txt
if var == HDMI
then 
    echo LCD > state.txt
    cd LCD-show/
    sudo ./LCD35-show
else
    echo HDMI > state.txt
        cd LCD-show/
    sudo ./LCD-hdmi
fi

I am hoping someone can show me what I did wrong, and hopefully explain what I missed in the process.


Solution

  • Be careful with your bash script comparisons. Wrap strings in quotes (or some other method), so it's not a syntax error when string-vars evaluate to empty. You can use == for string comparisons in bash, but = works in bash and sh.

    #! /bin/bash
    EXE=`basename "$0"`
    LCD_DIR="LCD-show"   
    STATE_FILE="state.txt"
    
    if [ ! -d "$LCD_DIR" ]; then
        echo "$EXE: $LCD_DIR does not exist"
        exit 1
    fi
    
    read var < state.txt  
    if [ "$var" = "HDMI" ]; then
        echo LCD > "$STATE_FILE"
        cd "$LCD_DIR"
        sudo ./LCD35-show
    else
        echo HDMI > "$STATE_FILE"
        cd "$LCD_DIR"
        sudo ./LCD-hdmi
    fi
    

    The difference between a good script and a great script is error handling. What happens when the dir LCD-show does not exist? (for whatever reason).