bash 错误 : syntax error: operand expected (error token is ")

标签 bash date math operands

我是 bash 脚本编写新手,我的一个脚本遇到了问题。我试图从一个充满 XML 文件的文件夹中读取 25 岁以下司机的出生日期并计算他们的年龄后,编写一份 25 岁以下司机的列表。一旦我确定它们低于 25,驱动程序数据的文件名就会保存到文本文件中。该脚本一直运行到某个点,然后停止。我收到的错误是:

gdate: extra operand ‘+%s’
Try 'gdate --help' for more information.
DriversUnder25.sh: line 24: ( 1471392000 -  )/60/60/24 : syntax error: operand expected (error token is ")/60/60/24 ")

这是我的代码:

#!/bin/bash

# define directory to search and current date
DIRECTORY="/*.xml"
CURRENT_DATE=$(date '+%Y%m%d')

# loop over files in a directory
for FILE in $DIRECTORY;
do
  # grab user's birth date from XML file
  BIRTH_DATE=$(sed -n '/Birthdate/{s/.*<Birthdate>//;s/<\/Birthdate.*//;p;}' $FILE)

  # calculate the difference between the current date
  # and the user's birth date (seconds)
  DIFFERENCE=$(( ( $(gdate -ud $CURRENT_DATE +'%s') - $(gdate -ud $BIRTH_DATE +'%s') )/60/60/24 ))

  # calculate the number of years between
  # the current date and the user's birth date
  YEARS=$(($DIFFERENCE / 365))

  # if the user is under 25
  if [ "$YEARS" -le 25 ]; then
    # save file name only
    FILENAME=`basename $FILE`
    # output filename to text file
    echo $FILENAME >> DriversUnder25.txt
  fi
done

我不确定为什么它正确输出前 10 个文件名然后停止。任何想法为什么会发生这种情况?

最佳答案

您需要引用 $BIRTH_DATE 的扩展,以防止值中的空格出现分词。 (引用所有参数扩展是一个很好的做法,除非您有充分的理由不这样做,正是因为这个原因。)

DIFFERENCE=$(( ( $(gdate -ud "$CURRENT_DATE" +'%s') - $(gdate -ud "$BIRTH_DATE" +'%s') )/60/60/24 ))

(根据您的评论,这可能至少允许 gdate 为您提供更好的错误消息。)

关于 bash 错误 : syntax error: operand expected (error token is "),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38998479/

相关文章:

angularjs - 如何使用 Angularjs 将 View 日期绑定(bind)到模型毫秒

javascript - 将方程写入 Javascript

objective-c - 评估字符串中的数学表达式? (NS字符串)

用户定义的c++常量变量

bash - 删除文件中不包含白名单字符的行

bash - sed/awk - 在跨越多行的模式之间打印文本

git - 通过 gitlab(或 git) merge 分支的最快方法?

linux - 简单的 linux 重定向

ios - 快速减去时间

ios - 日期格式化程序解析 JSON 日期