First, don't create an alias! from man bash
:
For almost every purpose, aliases are superseded by shell functions.
So unless you really know what the alias mechanism is, and you know you really need an alias, use a function instead.
The following function will get you to the last directory (with respect to sorting by name) of the current directory:
cdlast() {
local shoptnullglob=$(shopt -p nullglob)
shopt -s nullglob
local dirs=( */ )
$shoptnullglob
((${#dirs[@]})) && cd -- "${dirs[-1]}"
}
A few remarks: this will not take the hidden directories into account, unless have set the shell option dotglob
. If there are not directories in the current directory, the function does nothing (but has a return code of 1).
If you need to cd into the last modified directory, things get trickier (and hence more interesting):
cdlast() {
local shoptnullglob=$(shopt -p nullglob)
shopt -s nullglob
local dirs=( */ )
$shoptnullglob
((${#dirs[@]})) || return 1
local last=${dirs[0]}
for d in "${dirs[@]}"; do
[[ $d -nt $last ]] && last=$d
done
cd -- "$last"
}
If you like these functions, put them in you .bashrc
.