0

I would like to make a second backup from the latest created backup. So I tried the shell command:

last='ls -tr | tail -1'
cp -r /path/.../"$last" /path/.../backup/

but it copies a randome backup.

It is working perfect with .zip and .tar files but not with folders as I need it here.

I googled for a solution but couldn´t find anything related to this, I hope you can help me.

It would also be possible to use the name of directory which is for example:

2013-09-27-05-22-45

3 Answers3

0

I suggest using "last='ls -1tr |tail -1'" here. Without the '1' (one) in the command, the ls returns all of the files in your directory on a single line.

Ruairí N.
  • 645
  • 4
  • 8
  • 1
    That 1 is not needed. When you pipe the output the another command the 1 is automatically added anyway. – Tonny Sep 27 '13 at 16:44
0

Try "u" or "U" in stead of "t".

Depending on how the directory was created in the first place and how it is used it may be neccessary to use the creating date/time or the last access date/time.

And be careful !!!

If other programs/users are accesing these folders you will always have unexpected results.
(Those users may update the timestamp on the folder too !)

Given the format of the directory name you can probably better just sort by filename:

last='ls | tail -1'

If there are other files/folders that mess up the output just use:

last='ls -d [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9] | tail -1'

This will limit the output to just those folders whose name has the proper layout (4 digits, dash, 2 digits, dash, 2 digits, dash, etc)

Tonny
  • 6,252
  • 1
  • 17
  • 31
0

I use this a lot in my scripts or in my shell when I work with directories in my current directory.

alias lastd='ls -1drt * | tail -1'

The 'd' stands for directories only.

You can use it in you shell command line, like this :

mkdir some_dir
cd $(lastd)
Dave M
  • 4,494
  • 21
  • 30
  • 30
vincedgy
  • 101
  • 1
  • That is not what `-d` means. You'd get the same output by replacing `ls -1drt *` with `ls -1rt`. – kasperd Oct 13 '18 at 10:34