I am trying a small script to tell me if there is a file that exists less than 1k. It should report ERROR, otherwise the check is good.
I wrote this script down, however it never runs in the if/then statement. It always returns the echo ERROR.
MYSIZE=$(find /home/student/dir1 -type f -name '*' -size -1k)
if [ $? -eq 1 ]
then
echo "No Files Less Than 1k"
else
echo "ERROR: Found files less than 1k:
${MYSIZE}"
fi
I think you need to actually run MYSIZE, otherwise you are checking the exit code of previous command (setting the MYSIZE variable), which always succeeds. Please correct me anyone if I'm wrong.
After that first statement, the value of $? is the exit status of the last command executed by the subshell, find, and not that of the variable assignment. The problem is that the original poster's code is improperly interpreting the exit status of find. find will return 0 whether or not it finds anything, as long as no error occurred. The echo error branch is always running because no errors are occurring and the exit status is always 0.
Instead of...
if [ $? -eq 1 ]
... use ...
if [ ! "$MYSIZE" ]
... or, if you flip the then and else clauses, simply ...