I THINK what you may really want is to have a script merge.sh
that can be called any time to do X (where X is anything that should be done once, e.g. maybe start a daemon) but that script should not do X again if it's already done X. Given that, the fact it's being called in a loop sometimes is irrelevant but framing the question as "I have a command called from a loop" makes us think that the obvious solution is to just not call it in a loop. The only clue that that might not be the best solution is your statement that I want merge.sh to be functional with/out the other script
.
If I'm right then the solution would be to check if X has already been done rather than checking if this is the first time merge.sh
has been called, e.g. by testing for some process running or some environment variable having some value or some value set in some file (and, if the latter, then manage that somehow to ensure the value is cleared when necessary).
For example, I could imagine you having something like this:
$ cat start_foo
foo &
$ cat start_bar
bar &
$ cat start_all
while :; do
start_foo
start_bar
sleep 60
done
$ tail -1 .profile:
start_all &
so you have a script start_all
that runs continuously in the background making sure some set of other background processes are running and so it calls a script per process (e.g. start_foo
) to ensure that process (foo
) is running.
You don't want to start a new foo
process every minute but you also don't want to clutter start_all
with the details of what needs to happen to ensure foo
is running. Given that, you could write start_foo
as (pseudo-code):
$ cat start_foo:
if ! pgrep foo; then
foo &
fi
That will effective give you what you want, i.e. a script that only does something, foo &
, the first time it's called (in normal operation where foo
doesn't die) and will work whether called from a loop or not.
Whether the check in start_foo
is for a process running or a file existing or anything else is up to whatever start_foo
or foo
actually does.
In your case you MAY want something like:
#!/bin/sh
INPUT_LIST=/path_3/$1
outfile=${INPUT_LIST%.txt}.root
if [ ! -s "$outfile" ]; then
source /path/init
cd /path_2
echo "-----------------------------"
echo "Starting script:" $(basename $BASH_SOURCE)
echo "----------------------------- 0"
echo ${INPUT_LIST}
hadd -f "$outfile" @${INPUT_LIST}
fi
Check your quotes and capitalization btw - run your script through http://shellcheck.net and read Correct Bash and shell script variable capitalization.
You may also want something like:
$ cat merge.sh
#!/bin/sh
ucl=$2
INPUT_LIST=/path_3/$1
outfile=${INPUT_LIST%.txt}.root
if [ "$ucl" = 1 -o ! -s "$outfile" ]; then
source /path/init
cd /path_2
echo "-----------------------------"
echo "Starting script:" $(basename $BASH_SOURCE)
echo "----------------------------- 0"
echo ${INPUT_LIST}
hadd -f "$outfile" @${INPUT_LIST}
fi
and call it as:
ucl=1
while :; do
merge.sh whatever "$ucl"
ucl=""
done
or some other variation.