Home > Enterprise >  Trouble with Restarting a Script While Keeping Track
Trouble with Restarting a Script While Keeping Track

Time:05-02

I have a script I'm working on in bash where after any input is given, after the input is processed, the whole thing is restarted using exec bash "${BASH_SOURCE}", waiting to process the next input given by the user. This all works as intended, save for one catch. I need to run an if statement, but only so it runs when the script is first run. I've tried a multitude of solutions, but can't figure anything out. Any suggestions are welcome

CodePudding user response:

I'm not sure what you're trying to do in the end, but repeated exec's seem like it might be best handled another way.

That being said, here's a solution that works:

#!/usr/bin/bash

if [ "$FIRST_RUN" = "" ] ; then
  FIRST_RUN=no
  export FIRST_RUN
  echo first run
fi

read ans
echo "answer: $ans"
exec bash "${BASH_SOURCE}"

CodePudding user response:

You can have the script pass an argument to itself indicating that it's already done the initialization (or whatever it is):

#!/bin/bash

if [[ "$1" != --init-done ]]; then
    # do initialization/first run stuff here
else
    shift # Remove the --init-done option
fi

...process input...

exec "$BASH_SOURCE" --init-done

If the script doesn't take arguments, you can skip the shift.

  • Related