Alex, I get the jest of what you are attempting to do with inotifywait
, but when I attempted it, it would just hang and do nothing as the files were static at the point it was called. Looking at what you are attempting to accomplish. (build, run, measure disk usage of app
) it may be easier to just script it instead of putting inotifywait
in the middle of it.
While this is just a basic hack at getting the output you wanted. The script below will take the source file as the first argument (app.cpp
by default if no name given) and will compile the code using the name before .cpp
as the g++ output file name. It is a simple attempt to get the information you were looking for:
#!/bin/bash
src=${1:-app.cpp} ## set the source and output (exe) names
out=${src%.cpp}
printf "\n compiling 'g++ %s -o %s'\n\n" $src $out
[ -f $out ] && rm $out ## remove existing exe before builinding
g++ $src -o $out ## build new exe
[ -f $out ] || { ## validate new exe created
printf "error: compilation failed. exiting script.\n\n"
printf "usage: %s source.cpp (default: app.cpp)\n\n"
exit 1
}
[ -e $out ] || { ## validate it is executable
printf "error: file produced from compilation is not executable.\n"
exit 1
}
time ./$out 2>&1 ## compute elapsed time
exesz=$(du -h $out | awk '{print $1}') ## store disk usage (removing name)
## print results
printf "\n Source file: %s\n" "$src"
printf " output file: %s\n" "$out"
printf " size of exe: %s bytes\n\n" "$exesz"
exit 0
Example Output
$ ./watch.sh
compiling 'g++ app.cpp -o app'
Code Running
and being timed.
real 0m0.004s
user 0m0.001s
sys 0m0.002s
Source file: app.cpp
output file: app
size of exe: 16K bytes
The test code I used was a simple cout
:
#include <iostream>
using namespace std;
int main (void) {
cout << "Code Running" << endl << "and being timed." << endl;
return 0;
}
Incorporating iowaitnotify
Understanding better what you are attempting to accomplish, below is an addition (without all the validation checks) that will watch your source file and recompile on any change. It also avoids the use of eval
. There are several ways to accomplish this, this being one. You can add the validation checks from the script above if you desire:
#!/bin/bash
bldcmd=( ${@:2} ) ## array for build command
while inotifywait -q -e close_write -e delete $1; do
echo -e "\ncompiling: ${bldcmd[@]}"
# eval "${@:2}"
${bldcmd[@]}
time ./app
printf "\n app size: %s\n" $(du -h app | awk '{print $1}')
done
Output
$ ./watch . g++ app.cpp -o app
./ CLOSE_WRITE,CLOSE app.cpp
compiling: g++ app.cpp -o app
Code Running (ver. 6)
and being timed.
real 0m0.003s
user 0m0.001s
sys 0m0.002s
app size: 16K