Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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...

share|improve this question

2 Answers 2

up vote 7 down vote accepted

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
share|improve this answer
    
Worked great thanks! –  era878 Jun 6 '12 at 4:52
    
A slight improvement would be a semaphore file (touch .xxx) for 'last command', with a known first choice. –  david6 Jun 6 '12 at 8:10
1  
@david6 You may want to post your own answer. It's not clear to me why that would be better, or how you intend to implement it. –  Eliah Kagan Aug 13 '12 at 21:00

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.