cd to newest directory

0

Not strictly bash, but rather Bourne shell if possible. How can I programmatically cd to the newest directory? I want to install the latest package of whatever software, which is located in the newest directory. Older directories are kept for legacy systems.

Does not work:

find /test/sysadmin/aixinstall/programs/tcpd/* -type d | xargs ls -td | head -n 1 | xargs cd


edit:

I have an answer but it's kind of ugly so I'm giving somebody a chance to grace the internet with wisdom instead of a kluge.

bgStack15

Posted 2014-12-09T20:56:35.287

Reputation: 1 644

Answers

1

cdnewest () {
    cd "$(stat -c "%Y %n" "$1"/*/ | sort -nr | head -1 | cut -d " " -f 2-)"
}

cdnewest /test/sysadmin/aixinstall/programs/tcpd

I'm assuming that you're looking for the newest immediate subdirectory, not somewhere down in the hierarchy.

glenn jackman

Posted 2014-12-09T20:56:35.287

Reputation: 18 546

I do have the GNU stat (not a builtin on AIX or kornshell), but it returns a filename. I'm having a bit of trouble getting this trimmed down to just a directory! – bgStack15 – 2014-12-10T13:18:12.810

I think I got it now: cd "$( find "$1"/* -prune -type d 2>/dev/null | xargs stat -c "%Y %n" 2>/dev/null | sort -nr | head -n 1 | cut -d " " -f 2-)" – bgStack15 – 2014-12-10T13:22:28.893

1The trailing slash on my glob pattern limits the results to directories: demo: cd to a directory with both files and subdirectories and echo * versus echo */ – glenn jackman – 2014-12-10T14:44:23.427