Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cd into a random directory in bash?

I wish to figure out a way to change the working directory to a random directory in bash. By this I mean a pre-created directory that is not specified in any way. I've already tried just using cd * , but it doesn't recognize the wildcard character unless I have a letter in front of it, ie, cd a* . Does anyone know a quick, easy way to do this? A one-line solution would be great, but any answer will do. Thanks.

like image 874
null Avatar asked Feb 17 '23 23:02

null


1 Answers

shopt -s nullglob
dirs=(*/)
[[ $dirs ]] && cd -- "${dirs[RANDOM%${#dirs[@]}]}"

Whenever you want a single line, use a function. This also allows using locals and has other advantages.

like image 140
ormaaj Avatar answered Feb 27 '23 09:02

ormaaj