I just started my journey into bash scripting and I wrote a little script which copies certain files to my USB stick and external harddrive as a backup. So far it copies the entire directory with all files including those which I didn't change which naturally takes quite some time. In order to change that, I want it to compare the two files (on the pc and on the USB stick) with regards to the time when they were modified. So now I wonder how I can convert the output from
stat -c %y /test_folder/test.txt
into the format "YmDHMS"? Or maybe someone knows a better way to compare the files.
For comparison purposes you are probably better off using seconds since epoch (i.e.
stat -a %Y
) directly or even simpler use one of the bash built-in file tests[[ FILE1 -nt FILE2 ]]
or[[ FILE1 -ot FILE2 ]]
instead:However since the question as asked is about conversion, since
%y
is modification time, if you have a recent version of GNUdate
you could cheat and use that instead. Fromman date
:So
Alternatively, you could pass the seconds-since-epoch from
stat
todate
:For comparing modification (or access or inode change) time of files, you should use seconds since Epoch, it is easier to handle in comparisons.
stat
's-c
option has%Y
format specifier for getting the modification time in seconds since Epoch.To compare two files based on modification time, you can write a small function:
Input the two input files as first and second positional parameters, and the function will output which one is newer; when they have exactly the same modification times, no output will be shown.
Example: