从运行Perl脚本的Bash脚本返回Date值

时间:2014-06-05 15:22:23

标签: perl bash datetime posix

我正在尝试修复一个应该返回3个日期值的脚本:1周前,1个月前和3个月前。它使用来自CPAN的Perl模块,名为Time :: ParseDate,但我无法弄清楚它是如何工作的,也不知道它出错的地方。

getdate(){
echo $* | perl -MPOSIX -MTime::ParseDate -e'print strftime("%D",localtime(parsedate(<>)))'
return 0
}
oneweekago='getdate now - 1week'
onemonthago='getdate now - 1month'
threemonthsago='getdate now - 3month'

当我从shell运行时,我得到了这个输出:

-bash-4.1$ oneweekago='getdate now - 1week'
-bash:    : command not found
-bash:    : command not found
-bash-4.1$ onemonthago='getdate now - 1month'
-bash:    : command not found
-bash:    : command not found
-bash-4.1$ threemonthsago='getdate now - 3month'
-bash:    : command not found
-bash:    : command not found

我是unix脚本的新手,所以我确信这是我遗漏的一些基本语法,但我找不到它。顺便说一下,我已经安装了Time :: ParseDate模块并验证它已正确安装。

1 个答案:

答案 0 :(得分:3)

如果你只想在调用函数后立即输出值,这对我有用:

编辑:修改以获取返回值。你使用的是单引号,而不是背景。

#!/bin/bash

function getdate() {
    echo $* | perl -MPOSIX -MTime::ParseDate -e'print strftime("%D",localtime(parsedate(<>)))'
    return 0
}

oneweekago=$( getdate now - 1week )
# Using backtics this would look like:  oneweekago=`getdate now - 1week`
# However, I prefer $() for clarity.

onemonthago=$( getdate now - 1month)
threemonthsago=$(getdate now - 3month)

#getdate "now - 1week"
#getdate "now - 1month"
#getdate "now - 3month"

echo $oneweekago
echo $onemonthago
echo $threemonthsago