choosing a random folder in a folder

I need my script to choose a random folder within a folder and set that folders name as a variable.

I can list all folders within a folder using

#!/bin/bash

dir='/folder'
file=`/bin/ls -1 -l "$dir" | egrep '^d' | sort --random-sort | head -1`
path=`readlink --canonicalize "$dir/$file"` # Converts to full path

echo "The randomly-selected file is: $path"
echo "$file"
echo "$path"

Say my folder structure is

folder
|____folder01
|____folder02
|____folder03

By using the code above I can list the folders as so.

The randomly-selected file is: /folder/drwxr-xr-x 2 user user 4096 2012-04-14 14:53 folder01
drwxr-xr-x 2 user user 4096 2012-04-14 14:53 folder01
/folder/drwxr-xr-x 2 user user 4096 2012-04-14 14:53 folder01

I just want it to display 'folder01' and not 'drwxr-xr-x 2 user user 4096 2012-04-14 14:53 folder01'

Any help would be greatly appreciated.

Cheers
DV

---------- Post updated at 03:10 PM ---------- Previous update was at 02:25 PM ----------

I think the issue is with this command

ls -1 /folder/

I just need this command to just list directories and not files.

Try

find FOLDER -maxdepth 1 type -d

instead of

ls -l FOLDER
1 Like

I worked it out

#!/bin/bash

dir='/folder'
folder=`/bin/ls -d "$dir"/*/ | sort --random-sort | head -1`

echo "The randomly-selected file is: $folder";

output is a random folder in a folder

Boooo yacka shaaaaa

---------- Post updated at 03:49 PM ---------- Previous update was at 03:24 PM ----------

I like this a lot

find FOLDER -maxdepth 1 type -d

what do I put in the place of folder I can get it to work??

Also, say I want to search my documents folder but I only want the results to be folders or folders in folders. Is there away of doing that?

Cheers
DV

your folder :slight_smile:

"-type d" means "find" command will find only directories (folders).

find /root/folder/ -maxdepth 1 type -d

I get this error

find: paths must precede expression: type
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Sorry. Add '-a' :

find /root/folder/ -maxdepth 1 -a type -d

find /root/folder/ -maxdepth 100 -type d

---------- Post updated at 04:41 PM ---------- Previous update was at 04:29 PM ----------

My code

path=`find /root/folder/ -maxdepth 100 -type d | sort --random-sort | head -1`

if this returns a directory with spaces in for instance:

/root/folder/this is a folder

is there a way to replace the value of path with the same value but with the spaces replaced with

/root/folder/this\ is\ a\ folder/

Any qlues?

Cheers
DV