To run a line as a sh script (assuming POSIX):
You can explicitly specify the command:
x(["bash", "-c", '''shopt -s nullglob dirs=(*/) pwd cd -- "${dirs[RANDOM%${#dirs[@]}]}" pwd'''])
Note: it checks if you can cd into a random subdirectory. This change is not visible outside the bash script.
You can do this without bash:
You can also use glob :
from glob import glob randomdir = random.choice(glob("*/"))
The difference compared to os.listdir() is that glob() filters directories starting with a dot . . You can filter it manually:
randomdir = random.choice([d for d in os.listdir(os.curdir) if (not d.startswith(".")) and os.path.isdir(d)])
source share