0

I would like to make an executable shell-script that once launched execute a certain action, and if launched again in a second time undo the action. I've tried to define an environment variable to determinate if the action has been already executed, but I can't make it work.

#!/bin/bash
if [ -z ${CUSTOM_VARIABLE} ] 
then
    CUSTOM_VARIABLE=true
    export CUSTOM_VARIABLE 
    # do stuff here
else 
    # undo stuff here
    unset CUSTOM_VARIABLE
fi

Is this a correct approach? How can I fix the code

Thanks in advance

gic186
  • 786
  • 6
  • 18
  • 1
    This script is setting the CUSTOM_VARIABLE in the subshell started in order to run the script. Once the subshell exits and returns the variable you set in the subshell is not in the parent shell's environment. This is a pretty large part of shell coding, so I refer you to further conversation: https://stackoverflow.com/q/15541321/1531971 –  Nov 02 '18 at 15:51
  • 1
    This is what file systems are for. – chepner Nov 02 '18 at 20:12

1 Answers1

1

Note jdv's comment.

You cannot run your script as a standalone execution and have it alter the environment of the parent. Calling it x.sh,

x.sh

will never change your env. On the other hand, you can source it.

. x.sh

which reads it and executes its content in the current scope, so that would work. You aren't really creating a separate program doing that - just storing a scripted list of commands and using the source shorthand to execute them in bulk, so to speak.

You could also define it as a function for similar result -

$: x() {
   if [[ -z "${CUSTOM_VARIABLE}" ]]
   then export CUSTOM_VARIABLE=true
   else unset CUSTOM_VARIABLE
   fi
}

YMMV.

Good luck.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36