'Bash script logic fails occaisionally
This script checks a file size. If it is under the "minimum size" it should run the python script. However if it is over the minimum size the script should do nothing and exit. The problem that I am having is that sometimes when the file is over the minimum size the python script still runs. What am I not seeing?
#!/bin/bash
todays=$(date +%m-%d-%Y)
file_prefix=./csv/data_
file_suffix=.csv
file=${file_prefix}${todays}${file_suffix}
echo $file
minimumsize=64
actualsize=$(wc -c <"$file")
echo
if [ "$actualsize" -ge "$minimumsize" ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
#Script to run if filesize is under minimum size
/usr/bin/python3 /home/shannon/scripts/myscript.py
fi
Solution 1:[1]
It may be that the file is occasionally missing. You can solve that most easily by substituting a 0 size if the wc or stat fails. I'd recommend stat generally, since it doesn't actually read the file, which can be useful if the file is large or if the script hasn't got permission to read the file.
#!/bin/bash
file=./csv/data_$(date +%m-%d-%Y).csv
minimumsize=64
actualsize=$(stat -c%s $file 2>/dev/null || echo 0)
echo $file
echo
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
# Script to run if filesize is under minimum size
/usr/bin/python3 /home/shannon/scripts/myscript.py
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pi Marillion |
