Sunday, April 28, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  18] [ 0]  / answers: 1 / hits: 8873  / 1 Year ago, fri, march 3, 2023, 6:30:58

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


More From » scripts

 Answers
3

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

[#37835] Friday, March 3, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cretanol

Total Points: 320
Total Questions: 99
Total Answers: 115

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
cretanol questions
Fri, Dec 2, 22, 13:30, 1 Year ago
Thu, Dec 8, 22, 03:00, 1 Year ago
Mon, Aug 1, 22, 03:21, 2 Years ago
Fri, Sep 24, 21, 16:28, 3 Years ago
Sun, Apr 24, 22, 06:37, 2 Years ago
;