I am trying to test how old ago a file was created (in seconds) with bash in an if
statement. I need creation date, not modification.
Do you have any idea how to do this, without using a command like find
with grep
?
Bash uses `date ` command to display or change the current date and time value of the system. Date and time value can be printed in different formats by using this command. This command can also be used for calculating date and time value related tasks. `date` command without any option just prints the current system’s date and time value.
On Unix-like operating systems, test is a builtin command of the Bash shell that tests file attributes, and perform string and arithmetic comparisons. test provides no output, but returns an exit status of 0 for "true" (test successful) and 1 for "false" (test failed).
#!/bin/bash d="$ (date +%Y-%m-%d_%HZZZ.tmp.txt)" touch "$d" printf "%s " *.txt | LC_ALL=C sort | awk -v d="$d" 'f {print} d==$0 {f=1}' rm "$d" This creates a name that matches the current time. This creates a file with name matching the current time.
File test operators let you test various aspects of a file like if a file exists, is readable/writable, etc. Using file test operators can help to prevent errors in your Bash scripts. The code below is a boilerplate for the if statement. The if-else statement is a powerful tool you’ll often see in Bash scripts.
I'm afraid I cann't answer the question for creation time, but for last modification time you can use the following to get the epoch date, in seconds, since filename was last modified:
date --utc --reference=filename +%s
So you could then so something like:
modsecs=$(date --utc --reference=filename +%s)
nowsecs=$(date +%s)
delta=$(($nowsecs-$modsecs))
echo "File $filename was modified $delta secs ago"
if [ $delta -lt 120 ]; then
# do something
fi
etc..
Update A more elgant way of doing this (again, modified time only): how do I check in bash whether a file was created more than x time ago?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With