Get the latest directory (not the latest file)
Try this:
$ ls -td -- */ | head -n 1
-t
options make ls
sort by modification time, newest first.
If you want remove /
:
$ ls -td -- */ | head -n 1 | cut -d'/' -f1
ls -td -- ./parent/*/ | head -n1 | cut -d'/' -f2
Difference to Herson's solution is the slash after *
, which makes the shell ignore all non-dir files.
Difference to Gnouc, it'll work if you are in another folder.
Cut needs to know the number of parent directories (2) in order to delete trailing '/'. If you don't have that, use
VAR=$(ls -dt -- parent/*/ | head -n1); echo "${VAR::-1}"
Obligatory zsh answer:
latest_directory=(parent/*(/om[1]))
The characters in parentheses are glob qualifiers: /
to match only directories, om
to sort matches by increasing age, and [1]
to retain only the first (i.e. newest) match. Add N
if you want to get an empty array (normally you get a 1-elementy array) if there is no subdirectory of parent
.
Alternatively, assuming that parent
doesn't contain any shell globbing character:
latest_directory='parent/*(/om[1])'; latest_directory=$~latest_directory
If you don't have zsh but you have recent GNU tools (i.e. non-embedded Linux or Cygwin), you can use find
, but it's cumbersome. Here's one way:
latest_directory_inode=$(find parent -mindepth 1 -maxdepth 1 -type d -printf '%Ts %i\n' | sort -n | sed -n '1 s/.* //p')
latest_directory=$(find parent -maxdepth 1 -inum "$latest_directory_inode")
There's a simple solution with ls
, which works as long as no directory name contains newlines or (on some systems) non-printable characters:
latest_directory=$(ls -td parent/*/ | head -n1)
latest_directory=${latest_directory%/}