user836087 user836087 - 5 months ago 18
Bash Question

How to use shell variables in perl command call in a bash shell script?

How to use shell variables in perl command call in a bash shell script?

I have a perl command in my shell script to evaluate date -1.

How can i use $myDate in perl command call?

This is the section in my script:

myDate='10/10/2012'

Dt=$(perl -e 'use POSIX;print strftime '%m/%d/%y', localtime time-86400;")


I wana use $myDate in place of '%m/%d/%y'

Any help will be appriciated.

Thank you.

Answer

The same way you pass values to any other program: Pass it as an arg. (You might be tempted to generate Perl code, but that's a bad idea.)

Dt=$( perl -MPOSIX -e'print strftime $ARGV[0], localtime time-86400;' -- "$myDate" )

Note that code doesn't always return yesterday's date (since not all days have 86400 seconds). For that, you'd want

Dt=$( perl -MPOSIX -e'my @d = localtime time-86400; --$d[4]; print strftime $ARGV[0], @d;' -- "$myDate" )

or

Dt=$( perl -MDateTime -e'print DateTime->today(time_zone => "local")->subtract(days => 1)->strftime($ARGV[0]);' -- "$myDate" )

or simply

Dt=$( date --date='1 day ago' +"$myDate" )