LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   script Q : how do I force bash to perform the math? (https://www.linuxquestions.org/questions/linux-newbie-8/script-q-how-do-i-force-bash-to-perform-the-math-706109/)

kevinyeandel 02-20-2009 01:32 AM

script Q : how do I force bash to perform the math?
 
Hi

I want to know how old a file is so I've reduced the problem to give me two timestamps but:

echo `date +%s` - `stat -c %Z howoldisthisfile.txt`

gives

1235114433 - 1235093198

instead of

21235

I've tried () around various parts but just end up with syntax errors.

How do I persuade bash to give up the result without assigning to variables.

Many thanks
kevin

David the H. 02-20-2009 02:15 AM

The mathematical operation syntax for bash is $(( )). I also recommend $() for command nesting instead of using the ` backticks

Code:

echo "$(( $(date +%s) - $(stat -c %Z howoldisthisfile.txt) ))"
You do realize that on posix filesystems there is no "created time" flag, only a "last modified" one, I hope. It's impossible to know with certainty how old a file actually is, only how long it's been since it was last changed.

arckane 02-20-2009 02:22 AM

Expr way:
Code:

expr `date +%s` - `stat -c %Z howoldisthisfile.txt`
It's not pure bash as you need bc, but this'll work too:
Code:

echo "`date +%s`-`stat -c %Z howoldisthisfile.txt`" | bc

unSpawn 02-20-2009 02:24 AM

Code:

# quick
echo $[`date +%s` - `stat -c %Z howoldisthisfile.txt`]
# precise
echo `date +%s` - `stat -c %Z howoldisthisfile.txt`|bc -l
# Full M/C time
date --date="$(echo $[$(date +%s) - $(stat -c %Z .Xdefaults)] seconds ago)"


kevinyeandel 02-20-2009 02:35 AM

Quote:

Originally Posted by unSpawn (Post 3450713)
Code:

# quick
echo $[`date +%s` - `stat -c %Z howoldisthisfile.txt`]
# precise
echo `date +%s` - `stat -c %Z howoldisthisfile.txt`|bc -l
# Full M/C time
date --date="$(echo $[$(date +%s) - $(stat -c %Z .Xdefaults)] seconds ago)"


Thank you all for your help - quote a lot learned from your collective contributions!

Kevin


All times are GMT -5. The time now is 12:59 AM.