Modifying date in linux

How can I change the date modified/created of a file?

Is there a way to change the date when a file was modified/created (which is shown in Nautilus or with the ls -l command)? Ideally I am looking for a command which can change the date/time stamps of a whole bunch of files to a certain amount of time earlier or later (e.g. +8 hours or -4 days etc.).

6 Answers 6

As long as you are the owner of the file (or root), you can change the modification time of a file using the touch command:

By default this will set the file’s modification time to the current time, but there are a number of flags, such as the -d flag to pick a particular date. So for example, to set a file as being modified two hours before the present, you could use the following:

touch -d "2 hours ago" filename 

If you want to modify the file relative to its existing modification time instead, the following should do the trick:

touch -d "$(date -R -r filename) - 2 hours" filename 

If you want to modify a large number of files, you could use the following:

find DIRECTORY -print | while read filename; do # do whatever you want with the file touch -d "$(date -R -r "$filename") - 2 hours" "$filename" done 

You can change the arguments to find to select only the files you are interested in. If you only want to update the file modification times relative to the present time, you can simplify this to:

find DIRECTORY -exec touch -d "2 hours ago" <> + 

This form isn’t possible with the file time relative version because it uses the shell to form the arguments to touch .

As far as the creation time goes, most Linux file systems do not keep track of this value. There is a ctime associated with files, but it tracks when the file metadata was last changed. If the file never has its permissions changed, it might happen to hold the creation time, but this is a coincidence. Explicitly changing the file modification time counts as a metadata change, so will also have the side effect of updating the ctime .

To mention the simpler case when all files are in the same folder: touch -d «2 hours ago» /path/*.txt , for example.

The information about ctime as a metadata change time is from POSIX. I don’t know if the shell fragments in my answer would work with strict POSIX shell utilities. But they definitely work on Ubuntu, which is the context for answers on this site.

Easiest way — accessed and modified will be the same:

touch -a -m -t 201512180130.09 fileName.ext 
-a = accessed -m = modified -t = timestamp - use [[CC]YY]MMDDhhmm[.ss] time format 

If you wish to use NOW just drop the -t and the timestamp.

To verify they are all the same: stat fileName.ext

I tried to verify it using stat, but neither of the touch flags lead to a correct result. Modification date is adjusted, but changed and accessed date are actually changed to NOW

@ljoseph, take a look here: https://www.howtogeek.com/517098/linux-file-timestamps-explained-atime-mtime-and-ctime/#:~:text=%E2%80%9CModified%E2%80%9D%20means%20something%20inside%20the,will%20update%20the%20changed%20timestamp.

Using «-a» and «-m» together is probably unnecessary, «-a» is «change only the access time», and «-m» is «change only the modification time». If you want to update both, you don’t need to use any option.

Читайте также:  Linux на usb файловая система

Thanks for the help. This worked for me:

In the terminal go to the directory for date-edit. Then type:

find -print | while read filename; do # do whatever you want with the file touch -t 201203101513 "$filename" done 

You wil see a «>» after you hit enter, exept for the last time -> «done».

Note: You may want to change «201203101513»

«201203101513» = is the date you want for all the files in this directory.

Webpage is no longer, albeit it is 6 years later. Nonetheless, this is the answer I was looking for. For those who want to include seconds in their time, use .ss where ss is the number of seconds. (Note: this does not seem to control sub-second timings such as nanoseconds or milliseconds, which for me just appeared as zeros; however, this difference was permissible for my use-case.)

Touch can reference a file’s date all by itself, no need to call date or use command substitution. Here’s a bit from touch’s info page:

`-r FILE' `--reference=FILE' Use the times of the reference FILE instead of the current time. If this option is combined with the `--date=TIME' (`-d TIME') option, the reference FILE's time is the origin for any relative TIMEs given, but is otherwise ignored. For example, `-r foo -d '-5 seconds'' specifies a time stamp equal to five seconds before the corresponding time stamp for `foo'. If FILE is a symbolic link, the reference timestamp is taken from the target of the symlink, unless `-h' was also in effect. 

For example, to add 8 hours to a file’s date (filename of file quoted just in case of spaces, etc):

touch -r "file" -d '+8 hour' "file" 

Using a loop over all files in the current dir:

for i in *; do touch -r "$i" -d '+8 hour' "$i"; done 

I’ve heard that using a * and letting for pick the filenames itself is safer, but using find -print0 | xargs -0 touch . should handle most crazy characters like newlines, spaces, quotes, backslashes in a filename. (PS. try not to use crazy characters in filenames in the first place).

For example, to find all files in thatdir whose filenames start with an s , and add one day to those file’s modified timestamp, use:

find thatdir -name "s*" -print0 | xargs -0 -I '<>' touch -r '<>' -d '+1 day' '<>' 

This little script at least works for me:

#!/bin/bash # find specific files files=$(find . -type f -name '*.JPG') # use newline as file separator (handle spaces in filenames) IFS=$'\n' for f in $ do # read file modification date using stat as seconds # adjust date backwards (1 month) using date and print in correct format # change file time using touch touch -t $(date -v -1m -r $(stat -f %m "$") +%Y%m%d%H%M.%S) "$" done 

Adjusting the date of images based on meta info in the image would be pretty useful. ImageMagick’s identify can be used. e.g. ‘identify -verbose |grep -i date’, ‘identify -format %[exif:DateTime] ‘ might show ‘2015:01:08 10:19:10’ (not all images have exif data). This works(using sed to convert date to format touch can handle): ‘touch -d $(identify -format %[exif:DateTime] $f|sed -r ‘s/:/-/;s/:/-/;’) $f’

It’s been a long time since I wrote any kind of Unix program, but I accidentally set the year incorrectly on a bunch of Christmas photos, and I knew if I didn’t change the date from 2015 to 2014 it would be a problem later on.

Читайте также:  Видеорегистраторы на базе linux

Maybe, this is an easy task, but I didn’t find any simple way to do it.

I modified a script I found here, which originally was used to modify the date by minus one month.

Here’s the original script:

#!/bin/bash # find specific files files=$(find . -type f -name '*.JPG') # use newline as file separator (handle spaces in filenames) IFS=$'\n' for f in $ do # read file modification date using stat as seconds # adjust date backwards (1 month) using date and print in correct format # change file time using touch touch -t $(date -v -1m -r $(stat -f %m "$") +%Y%m%d%H%M.%S) "$" done 

Here’s my modified script that forced the date to the year «2014»:

#!/bin/bash # find specific files #files=$(find . -type f -name '*.JPG') # use newline as file separator (handle spaces in filenames) IFS=$'\n' for f in $* do # read file modification date using stat as seconds # adjust date backwards (1 month) using date and print in correct format # change file time using touch touch -t $(date -v +1y -r $(stat -f %m "$") +2014%m%d%H%M.%S) "$" done 

I now realize I could have done a more generic version:

#!/bin/bash # find specific files #files=$(find . -type f -name '*.JPG') # use newline as file separator (handle spaces in filenames) IFS=$'\n' for f in $* do # read file modification date using stat as seconds # adjust date backwards (1 month) using date and print in correct format # change file time using touch (+1y adds a year "-1y" subtracts a year) # Below line subtracts a year touch -t $(date -v -1y -r $(stat -f %m "$") +%Y%m%d%H%M.%S) "$" # Below line adds a year # touch -t $(date -v +1y -r $(stat -f %m "$") +%Y%m%d%H%M.%S) "$" done 

To use this file you would need to write it and

Источник

How to Work with Date and Time in Bash Using date Command

Date command is an external bash program that allows to set or display system date and time. It also provides several formatting options. Date command is installed in all Linux distros by default.

Find Date Command Location

Type date command in terminal which will display current date and time.

Check Date in Linux

Change Linux System Date and Time

Using date command, system date, time and timezone can be modified and the change has to be synced with the hardware clock.

$ date --set="Thu Nov 12 13:06:59 IST 2020" $ hwclock --systohc

Set Linux System Date and Time

Formatting Options

A good place to get the list of formatting options will be the man page.

Let’s see some of the most common formatting options that we will use.

  • To apply formatting use “+ followed by “formatter“.
  • To get a list of formatting options for GNU\LINUX take a look at the linked man page.
  • To get a list of formatting options for BSD take a look at the linked man page.

The two important parts of the date command is using Format +% and –date option.

Now let’s apply some formatting on the date command. To apply formatting, add plus sign (+) followed by %formatter as shown in examples.

Handling Date in Linux

Let’s take a look at how to use date related formatters in a simple shell script called ‘date.sh‘.

# PRINT YEAR,MONTH,DAY AND DATE. echo "We are in the year = $(date +%Y)" echo "We are in the year = $(date +%y)" # Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year. echo "We are in the month = $(date +%m)" echo "We are in the month = $(date +%b)" echo "We are in the month = $(date +%B)" # Difference between %B and %b is, %B will print full month name while %b will print abbreviated month name. echo "Current Day of the month = $(date +%d)" echo "Current Day of the week = $(date +%A)" echo "Current Day of the week = $(date +%a)" # Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday name. # Instead of formatting to get the date, we can use %D which will print the date as %m/%d/%y or %F which prints in %Y-%M-%d format. echo "Date using %D = $(date +%D)" echo "Date using %F = $(date +%F)"

Find Date and Time using Script

Handling Time in Linux

Let’s take a look at how to use time related formatters in a simple shell script called ‘time.sh‘.

# PRINT HOURS, MINS, SECONDS, NANO SECONDS echo Hours = $(date +%H) echo Minutes = $(date +%M) echo Seconds = $(date +%S) echo Nanoseconds = $(date +%N) echo Epoch Time = $(date +%s) echo "current time = $(date +%H:%M:%S:%N)" # can also use %T which displays Time in HH:MM:SS format. echo "current time in 24 hour format = $(date +%T)" # can also use %r to display time in 12 hour format. echo "current time in 12 hour format = $(date +%r)"

Find Time in Linux Using Script

With –date or -d Flag

With —date or -d flag input can be passed as string and date command knows to handle it smartly.

Читайте также:  Как посмотреть символьные ссылки linux

Let’s see some examples to understand how it works.

# Print yesterday's date and time. echo "Yesterday = $(date -d "Yesterday")" # Print Tomorrow date and time. echo "tomorrow = $(date -d "tomorrow")" # Find what is the date and time before 10 days from now. echo "Before 10 days = $(date -d "tomorrow -10 days")" # Find last month and next month echo "Last month = $(date -d "last month" "%B")" echo "Next month = $(date -d "next month" "%B")" # Find last year and next year echo "Last Year = $(date -d "last year" "+%Y")" echo "Next Year = $(date -d "next year" "+%Y")" # Forecast the weekday echo "2 days away from today and it comes on weekdays? = $(date -d "Today +2 days" "+%A")

Check Date Using Formatting

Common Operations

calculate the number of days between 2 given dates.

$ echo $(( ( $(date -d "2020-11-10" "+%s") - $(date -d "2020-11-01" "+%s") ) / 86400))

Find the given year is leap year or not.

$ for y in ; do date -d $y-02-29 &>/dev/null && echo $y is leap year; done

Find Leap Year in Linux

Assigning output of date command to a variable.

$ TODAY=$(date +%Y-%m-%d) OR $ TODAY1=$(date +%F) $ echo $TODAY $ echo $TODAY1

Assign Date to Variable

Create log files with the date added to the filename.

Adding date and time while creating log files, backup, or text files is a common operation that we will encounter most often. Let’s take an example, to take a backup, we have created a shell script.

This script will take a backup from 00:00 to 23:59 and scheduled to run daily at 00:00 of the next day. We want to create log files with yesterday’s date format.

CUSTOM_FORMAT=$(date —date «Yesterday» «+%d-%y-%H:%M») LOG_FILE=/var/log/custom_application/application_$.log echo «Script started» >> $ . CODE BLOCKS . echo «Script completed» >> $

That’s it for this article. In this article, we have seen how to use bash date and time in Linux. Let us know your feedback.

Источник

Оцените статью
Adblock
detector