My various side-project folders contain tens of side projects that are yet to succeed. And I’m only ever really interested in the latest one (hehe). So instead of remembering its name, I want to change directories right into it.
That’s precisely what this bash function does:
cdl() {
# Change Directory to Latest
local latest_dir=$(ls -td -- */ | head -n 1)
if [[ -d "$latest_dir" ]]; then
cd "$latest_dir"
else
echo "No directories found!"
fi
}
Breakdown
ls -t
orders the ls entries by the modified time - which is precisely what we want.ls -d
prevents the ls from searching the directories recursively. They are listed as plain files, nothing special about them now.*/
is actually important. With only the asterisk wildcard*
, files are included in the ls output too. Adding the slash/
limits the ls to directories - but thanks to the previous modifier, ls doesn’t descend into them
I just put this function in my .aliases
file, sourced in .zshrc
- usual stuff.