I'm trying to display to a user when their authentication is about to expire when their .zshrc
is sourced on either MacOS or Linux. When running directly in zsh
everything appears fine. However when running source ~/.zshrc
on MacOS
it throws the error:
└─> source ~/.zshrc
check_token:35: bad math expression: operator expected at `23:17:10'
It appears to want to perform an operation on the following line:
ISO_expiry_date="${expiry_year}/${expiry_month}/${expiry_day}${expiry_time}"
The full code snippet it below:
check_token() {
command="auth"
token -s
if [ $? -ne 0 ]; then
echo "Authetication not present, running $command"
eval $command
if [[ $? -ne 0 ]] && [[ $? -ne 130 ]]; then
check_token
fi
fi
token -s
if [ $? -eq 0 ]; then
token=`tokenlist | grep string`
ISO_expiry_date=""
if [[ `uname` == "Linux" ]]; then
expiry_date=`echo $token | awk '{print $3}'`
# Alter from American date format to ISO
expiry_date_parts=(${(s[/])expiry_date})
expiry_time=`echo $token | awk '{print $4}'`
ISO_expiry_date="$expiry_date_parts[3]/$expiry_date_parts[2]/$expiry_date_parts[1] $expiry_time"
elif [[ `uname` == "Darwin" ]]; then
expiry_day=`echo $token | awk '{print $6}'`
printf -v expiry_day "d" $expiry_day
month=`echo $token | awk '{print $5}'`
expiry_month=`date -j -f "%b" "$month" "%m"`
expiry_year=`echo $token | awk '{print $8}'`
expiry_time=" `echo $token | awk '{print $7}'`"
ISO_expiry_date="${expiry_year}/${expiry_month}/${expiry_day}${expiry_time}"
fi
if [[ $ISO_expiry_date -ne "" ]]; then
echo "Ticket will expire at $ISO_expiry_date"
else
echo "Current ticket: $token"
fi
fi
}
tokenlist
displays something similar to the following on Mac:
Issued Expires Principal
Sep 1 13:17:14 2022 Sep 1 23:17:10 2022 string
zsh version:
zsh --version
zsh 5.8.1 (x86_64-apple-darwin21.0)
MacOS version:
sw_vers
ProductName: macOS
ProductVersion: 12.5.1
BuildVersion: 21G83
CodePudding user response:
[[ $ISO_expiry_date -ne "" ]]
does a numeric comparison, which fails because the value of $ISO_expiry_date
can't be converted to a number. You should instead use either
[[ $ISO_expiry_date != "" ]]
if you want to compare arbitrary strings, or
[[ -n $ISO_expiry_date ]]
if you want to specifically check if a string is not empty. In Zsh programming, to check for empty strings, the latter is generally preferred over the former.
See https://zsh.sourceforge.io/Doc/Release/Conditional-Expressions.html for more info.