This is a self contained solution using a heredoc. At first glance it may seem an elaborate and inperfect solution, it does have its uses in that it's resilient and it works well when deploying across more than one machine, requires no special monitoring or permissions of external files, and most importantly, there are no unwanted surprises with environment.
This example uses bash, but it will work with sh if the $thisfile
variable is set manually, or another way.
This example assumes that 20
is already in the script file as mymonitorvalue
, and uses argument $1 as a proof of concept. You would obviously change newval="$1"
to whatever calculates the quota:
Example usage:
#bash $>./script 10
Value from previous run was 20
Value from this test was 10
Updating value ...
#bash $>./script 10
not doing anything ... result is the same as last time
#bash $>
Script:
#!/bin/bash
thisfile="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ; thisfile="${DIR}${0}"
read -d '' currentvalue <<'EOF'
mymonitorval=20
EOF
eval "$currentvalue"
function changeval () {
sed -E -i "s/(^mymonitorval\=)(.*)/mymonitorval\="$1"/g" "$thisfile"
}
newvalue="$1"
if [[ "$newvalue" != "$mymonitorval" ]]; then
echo "Value from previous run was $mymonitorval"
echo "Value from this test was "$1""
echo "Updating value ..."
changeval "$newvalue"
else
echo "not doing anything ... result is the same as last time"
fi
Explanation:
thisfile=
can be set manually for script location. This example uses the automated solution from here: https://stackoverflow.com/a/246128
read -d
...EOF
is the heredoc which is saved into variable $currentvalue
eval "$currentvalue"
in this case is the equivalent of typing mymonitorval=10
into a terminal
function changeval...}
updates the contents of the heredoc in place (it changes the physical .sh script file)
newvalue="$1"
is for the purpose of testing. $newvalue
would be determined by whatever your script is that is calculating quota
if....
block is to perform two alternate sets of actions depending on whether $newvalue
is the same as it was last time or not.