Liam F. O'Neill
Liam F. O'Neill

Reputation: 155

Returning Date values from Bash script that runs a Perl Script

I am trying to fix a script that is supposed to return 3 date values: 1 week ago, 1 month ago and 3 months ago. It uses a Perl module from CPAN called Time::ParseDate but I cannot figure out how it works nor where it is going wrong.

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'

When I run this from the shell I get this output:

-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

I am totally new to unix scripting so I am sure this is some basic syntax I am missing but I cannot find it. Btw I have already installed the Time::ParseDate module and verified it is installed properly.

Upvotes: 1

Views: 412

Answers (1)

user3183018
user3183018

Reputation: 364

If you just want to output the values immediately upon calling the function this works for me:

EDIT: Modified to get the return value. You were using single quotes, not backtics.

#!/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

Upvotes: 3

Related Questions