Shell Script to Toggle Between Two Commands

I need help creating a shell script to toggle between two commands.
When it is run command1 is executed then if it is run again it executes command2 and so on…

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

One good way of accomplishing this is for the script to create a blank “configuration file”:

  • The 1st time the script runs, it sees the file doesn’t exist, creates it, and runs command1.
  • The 2nd time the script runs, it sees the file does exist, deletes it, and runs command2.
  • The 3rd time the script runs, it sees the file doesn’t exist, creates it, and runs command1.
  • The 4th time the script runs, it sees the file does exist, deletes it, and runs command2.

And so forth.

Here’s a script that does that:

#!/bin/sh
# This shell script is PUBLIC DOMAIN. You may do whatever you want with it.

TOGGLE=$HOME/.toggle

if [ ! -e $TOGGLE ]; then
    touch $TOGGLE
    command1
else
    rm $TOGGLE
    command2
fi

Solution 2

(As a complement to the main answer)

To make it display a message after running the commands, and also showing an icon – example for toggling touchpad off and on (source, also here):

#!/bin/sh
# This shell script is PUBLIC DOMAIN. You may do whatever you want with it.

TOGGLE=$HOME/.toggle_touchpad

if [ ! -e $TOGGLE ]; then
    touch $TOGGLE
    xinput disable 14
    notify-send -u low -i mouse --icon=/usr/share/icons/HighContrast/256x256/status/touchpad-disabled.png "Trackpad disabled"
else
    rm $TOGGLE
    xinput enable 14
    notify-send -u low -i mouse --icon=/usr/share/icons/HighContrast/256x256/devices/input-touchpad.png "Trackpad enabled"
fi

(in the above commands 14 is a variable to be identified with xinput list)

Solution 3

You can write a file with your last command. Then when it is run again you read the file, and see which command was executed.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply