Convert a date stored in a variable to epoch date

I am not able to pass date stored in a variable as an argument to date command. I get current date value for from_date and to_date

 
#!/usr/bin/ksh
set -x
for s in server ; do
ssh -T $s <<-EOF
from_date="12-Jan-2015 12:02:09"
to_date="24-Jan-2015 13:02:09"
echo \$from_date
echo \$to_date
epoch_from_date="`date +%s -d \$from_date`"
epoch_to_date="`date +%s -d \$to_date`"
echo \$epoch_from_date
echo \$epoch_to_date
EOF
done

There seems to be a misapprehension of here documents. man bash (but similar for ksh):

On the other hand, simple commands are NOT run nor are assignments performed. So, some rearrangements and some simple modification get you nearer to your goal, but you can't achieve it:

for s in server ; do
from_date="12-Jan-2015 12:02:09"                        # works in same shell
to_date="24-Jan-2015 13:02:09"                          # same
ssh -T $s <<-EOF
$(echo $from_date)                                      # same as just $from_date 
$(echo $to_date)                                        # same
$(epoch_from_date=\"`date +%s -d "$from_date"`\")       # works, but in sub shell
$(epoch_to_date=\"`date +%s -d "$to_date"`\")           # same
$(echo $epoch_from_date)                                # var is gone with sub shell
$(echo $epoch_to_date)                                  # same
EOF
done

Don't forget - the here document is fed to ssh 's stdin. It should contain (malleable) commands and/or data for ssh , not the shell.

1 Like

Try:

ssh -T $s <<- "EOF"
...
EOF
1 Like

Thanks for clarification!

I tried this modified code

 
#!/usr/bin/ksh
set -x
for s in server ; do
ssh -T $s <<- "EOF"
from_date="12-Jan-2015 12:02:09"
to_date="24-Jan-2015 13:02:09"
echo $from_date
echo $to_date
epoch_from_date="`date +%s -d "$from_date"`"
epoch_to_date=\"`date +%s -d "$to_date"`\"
echo $epoch_from_date
echo $epoch_to_date
EOF
done

But do not get the desired result. Last two echo results to

%s
"%s"

Sorry, my post #2 was due to a misapprehension from my side. The only more or less reasonable hint was "take care of the quoting \"`date +%s -d "$from_date"`\" of the variable...

1 Like

I get :

12-Jan-2015 12:02:09
24-Jan-2015 13:02:09
1421060529
"1422100929"

Ar you sure for s in server is correct. Do you have a server name there, or is it a variable and do you need to put a $ sign in front?
Is the server a Linux system and/or does it have GNU date?

1 Like

And, put the set -x into the here document...

1 Like

It was my mistake, I changed the code to

 
epoch_from_date="`/progs/bin/date +%s -d "$from_date"`"
epoch_to_date=\"`/progs/bin/date +%s -d "$to_date"`\"
 

and its working fine. Thanks for resolving the issue.