Change directory to last match in *nix cd command Change directory to last match in *nix cd command unix unix

Change directory to last match in *nix cd command


Try this:

cd `ls -rd folder_*`

There is always a shorter code :)


ls isn't suited for this type of use. You can use file globbing and an array:

dirs=(folder_*/); cd "${dirs[@]: -1}"

The glob is guaranteed to be expanded in lexical order. The array slice accesses the last member of the array.

You could create a function that would automatically remove the array:

cdl () { declare -a dirs=(${1:-folder_}*/); cd "${dirs[@]: -1}"; }

This defaults to a prefix of "folder_", but it will accept an argument to use another prefix:

cdl dirname-

declare inside a function makes the variable local to the function.

If you're using Bash 4.2, you can access the last array element directly instead of using a slice as above:

cd "${dirs[-1]}"


try this

cd `ls -ld folder_* | awk '{print $9}' | sort | sed -e '$!d'`

But I guess you'll have to name your folders folder_01, folder_02 instead of folder_1, folder_2, ...