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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With