简体   繁体   中英

Arithmetic syntax error only on alpine linux

I'm really new to bash and just started today to scripting a little scheduler. After testing it on mac and ubuntu everything worked fine. But when I wanted to execute it within an alpine linux an error is thrown: arithmetic syntax error. I can't understand why this is the case and couldn't find a solution on uncle google. I hope someone could help me.

This is the expression:

[ $((10#$(date +"%H%M") != 10#$START_TIME)) = 1 ]

In context showing how this is run:

#!/bin/bash

START_TIME=2100
END_TIME=2200

#  arithmetic syntax error
while [ $((10#$(date +"%H%M") != 10#$START_TIME)) = 1 ]; do 
    sleep 10;
done

This code is relying on syntax that isn't POSIX-specified to ensure that values are parsed as decimal numbers even if they start with leading 0s.

The easy answer is "don't do that" -- which is to say, either use string comparisons rather than numeric ones, or trim your leading 0s a different way if you need to run with baseline-POSIX interpreters.

Sticking with the numeric route: It's inefficient to use sed for the job, for example, but it works:

START_TIME=2100 # this already doesn't start with a 0
while [ $(( $(date +"%H%M" | sed -e 's/^0+//') != START_TIME )) = 1 ]; do
  sleep 10
done

Or, using a string comparison directly:

START_TIME=2100 # exactly four digits
while [ "$(date +"%H%M")" != "$START_TIME" ]; do
  sleep 10
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM