'Trouble with Restarting a Script While Keeping Track
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
Solution 1:[1]
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}"
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wes Hardaker |
| Solution 2 | Gordon Davisson |
