0

What I really want is a NOT and write. I have files that are either 1 or 0, like

/sys/class/leds/platform::mute/brightness
/sys/class/leds/platform::micmute/brightness

What I want is a way to turn the 1's to 0's and flush that result to the file. Something like toggle would otherwise do if the modules authors implemented it.

What's the most golfy-and-elegant way to do this without calling a custom script?

Evan Carroll
  • 30,763
  • 48
  • 183
  • 315

1 Answers1

1

A general purpose function may be:

toggle () { <"$1" tr 01 10 >"$1"; }
# or
toggle () { <"$1" tr 01 10 | tee "$1"; }
# or
toggle () { <"$1" tr 01 10 | sudo tee "$1"; }
# or
toggle () { <"$1" tr 01 10 | sudo tee "$1" >/dev/null; }

(depending on if you want to see the new value; and if you need to use sudo). You use it like this:

toggle /sys/class/leds/platform::mute/brightness

Don't use it for files that can be truncated effectively. In /sys/ it works though.


This section is more detailed. It concentrates on /sys/class/leds/*/brightness. We can start with:

(cd /sys/class/leds/platform::mute && <brightness tr 01 10 >brightness)

Notes:

  • This wouldn't work with files that can be truncated effectively.
  • If you need sudo then sudo sh -c 'cd /sys/… && <brightness tr 01 10 >brightness' or with tee, like above. A shell function may be handy:

    toggLED () { sudo sh -c 'cd "/sys/class/leds/$1" && <brightness tr 01 10 >brightness' sh "$1"; }
    toggLED platform::mute
    

    Or this quick and dirty version that supports wildcards (and code injection):

    toggLED () { sudo sh -c "cd /sys/class/leds/$1 && <brightness tr 01 10 >brightness"; }
    toggLED 'pla*:mute'
    toggLED 'foo; date'   # code injection possible
    
  • In practice you can chown and/or chmod the brightness file(s) (after each reboot) and go without sudo to avoid having to type the password again and again:

    sudo chmod a+w /sys/class/leds/*/brightness
    toggLED () ( cd "/sys/class/leds/$1" && <brightness tr 01 10 >brightness )
    toggLED platform::mute
    

    An alternative is NOPASSWD in sudoers.

  • I have dell::kbd_backlight where max_brightness is 2. A general simple way to kinda cover it is with tr 012 100 (which can be generalized further to tr 0123 1000 etc.). A specific way to cycle fully is tr 012 120. A general way to cycle fully requires reading max_brightness and adjusting the transformation; not really golfy-and-elegant.