I have a shell script(A) that is being called by another script(B).In this script(A) I am creating some directories and moving some files as preparatory work for the rest of the script to work fine. Script(A) is called upon by script(B) in an iterative manner, I only want the creating of directories and moving of files to occur only once i.e during the very first loop. What can I do to execute a part of my script only once?
Iterative Control Flow in Subshelled Script
shell
You need some relatively unique quality of the environment upon which to rely. This is not easy to come by - especially if you are calling a separate script iteratively in a loop and expect it to behave differently for each occurrence (why not portions of the same script in that case?).Anyway, the common thing to do is to use a lockfile - or something like it - for these kinds of things. In order to do this though, you do need that unique bit of environment. Consider the following:sh -c 'echo $PPID $$       for i in 1 2 3 4 5       do sh -c echo \\$PPID\       done'OUTPUT25711 289292892928929289292892928929If you can rely on the caller providing its pid to you in the environment variable $PPID it may be just what you need. For example:#!/bin/sh#script aLOCKDIR=${TMPDIR:-/tmp}/${0##*/}.$PPIDinit() { mkdir $LOCKDIR || exit#        do other initialization tasks}loop() { : do the iterable tasks here; }[ -d $LOCKDIR ] || initloop...and...#!/bin/sh#script ba='/path/to/script/a'for stuff in $thingsdo $a $stuffdonerm -rf ${TMPDIR:-/tmp}/${a##*/}.$$Seriously, though, I haven't encountered many situations at all in which doing this kind of thing is a good idea - if I am calling another shell-script iteratively and I must rely upon its environment then I would probably . source the script's contents into the current shell and run it that way. I would do this, that is, if I was very sure the script I was running was securely written.