0

I am getting the following error when running my shell script

Code

#!/bin/bash
printf "Memory\t\tDisk\t\tCPU\n"
end=$((SECONDS+3600))
while [ $SECONDS -lt $end ]; do
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s\t\t", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}')
echo "$MEMORY$DISK$CPU"
sleep 5
done

Error

 sh ./testeusage.sh
 Memory          Disk            CPU
 ./testeusage.sh: 4: [: -lt: unexpected operator

What is wrong with the -lt line?

Thanks.

JNevill
  • 46,980
  • 4
  • 38
  • 63
  • 2
    Sounds like `sh` isn't `bash` on your machine, but some other shell that doesn't implement `SECONDS`. Execute the script with `bash`, or make the script executable and let `./testeusage.sh` make use of the hashbang. – chepner Sep 08 '22 at 17:14
  • Given that `SECONDS` is initialized to 0, not the current time, you could simply loop with `while (( SECONDS < 3600 )); do`. (Or just iterate 720 times.) – chepner Sep 08 '22 at 17:15
  • Using `sh` to run a shell that starts with `#!/bin/bash` is inherently self-contradictory. `#!/bin/bash` says it should be run with **bash**. Run `bash ./testusage.sh`, not `sh ./testusage.sh` – Charles Duffy Sep 08 '22 at 17:18
  • ...btw, this confusion is part of why naming shell scripts -- and especially _bash_ scripts, which are not POSIX sh scripts -- with `.sh` extensions is a Bad Idea. See also [Commandname Extensions Considered Harmful](https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/), the essay the #bash IRC channel has linked on the topic for well over a decade now. – Charles Duffy Sep 08 '22 at 17:18

0 Answers0