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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.