With the bash script below I am getting an error;
line 16: [: : integer expression expected
but I can't figure out why? The error lies in if [ "$(log_date)" -le "$days_in_ms" ]; then
Can anyone help and explain as BASH if statements confuse me
#!/bin/bash
region="eu-west-1"
retention_days="28"
days_in_ms="$(date +%s%3N --date=-"$retention_days"+days)"
log_date () {
aws logs describe-log-streams --region $region --log-group-name "$groups" | jq -r '.logStreams[].lastEventTimestamp' > /dev/null 2>&1
}
log_name () {
aws logs describe-log-streams --region $region --log-group-name "$groups" | jq -r '.logStreams[].logStreamName' > /dev/null 2>&1
}
mapfile -t logGroups < <(aws logs describe-log-groups --region $region | jq -r '.logGroups[].logGroupName') > /dev/null 2>&1
for groups in "${logGroups[@]}"; do
if [ "$(log_date)" -le "$days_in_ms" ]; then
log_name
fi
done
Note the details of the error message:
[: : integer expression expected
See the blank before the second :
? That's where the value that [
is trying to operate on would be, if there were one. It's blank, meaning something [
was told would be a number is not there at all.
To provide an example of how this works:
$ [ foo -ge 1 ]
-bash: [: foo: integer expression expected
Note that the foo
is given in the same position where you have a blank. Thus, a blank value is being parsed as a number.
Your log_date
function does not return any output, because of its >/dev/null
. Consequently, your code tries to parse the empty string it returns as a number, and (correctly) complains that it's getting an empty string in a position where an integer is expected.
In the future, run set -x
to enable logging of each command before it's run, or invoke your script with bash -x yourscript
when debugging, to identify these issues.