0

I want to have a launcher that runs a Bash commands that toggle a setting; switching the setting one way requires one command and switching it the other way requires another command. If there is no easy way to query the system to find out the status of that setting, how should Bash remember the status of the setting so that it can run the appropriate command?

An obvious solution would be to save the status as files and then check for the existence of those files to determine the appropriate command to run, but is there some neater way, perhaps one that would use volatile memory?

Here's an attempt at a toggle script using temporary files:

#!/bin/bash

main(){

    settingOn="/tmp/red_on.txt"
    settingOff="/tmp/red_off.txt"

    if [[ ! -e "${settingOff}" ]] && [[ ! -e "${settingOn}" ]]; then
        echo "no prior use detected -- creating default off"
        touch "${settingOff}"
    fi

    if [ -f "${settingOff}" ]; then
        echo "switch on"
        redshift -o -t 1000:1000 -l 0.0:0.0
        rm -f "${settingOff}"
        touch "${settingOn}"
    elif [ -f "${settingOn}" ]; then
        echo "switch off"
        redshift -x
        rm -f "${settingOn}"
        touch "${settingOff}"
    fi

}

main
d3pd
  • 7,935
  • 24
  • 76
  • 127
  • So you don't want the setting to persist in different sessions – 123 Nov 16 '15 at 10:11
  • Using two separate files invites a race condition. You should use some sort of mutex to make sure that the state is only changed when no other process is in the process of changing the state. A simple, portable approach involves creating a directory, and yielding if that fails. Remove the directory when you are done changing state. – tripleee Nov 16 '15 at 10:13
  • I agree with tripleee, just use a single file called togglestate or something. Delete it for toggle off and create it for toggle on – 123 Nov 16 '15 at 10:16
  • @123 yes, `togglestate` is a good idea, but it is well known in unix lore to use a call to `mkdir dirName` to have an atomic control of a toggle. Files don't have this feature. Good luck to all. – shellter Nov 16 '15 at 12:08
  • @shellter Can you explain a bit more about why to use a directory instead of a file. I've always used files and am wondering if i need to change! – 123 Nov 16 '15 at 12:50
  • 1
    @123 : Searching for `[bash] mkdir atomic` makes me realize that "well known unix lore" was a. an overstatement , b. in some cases, out-of-date . See http://stackoverflow.com/questions/169964/how-to-prevent-a-script-from-running-simultaneously/1560651?s=4|0.7303#1560651 for pretty good discusssion. c. if you're using `flock` then you're up-to-date. Good luck to all. – shellter Nov 16 '15 at 13:20
  • @shellter I normally use `lockfile` but after searching it seems to work in pretty much the same way as far as can tell. That question/answers are pretty informative though , thanks :) – 123 Nov 16 '15 at 13:31

0 Answers0