-1

I want to get and open a random file from a folder.

Let's say I have a group of files in:

/Users/Me/Downloads/Stuff/

I want a command that return the filepath of a randomly chosen file in the Stuff folder.

aka.

randFile = /Users/Me/Downloads/Stuff/randVid.exe

then I want to open with

open -a "QuickTime Player" randFile

I understand how to open the file with the desired program but I am having trouble finding out the solution to getting a randomly chosen file since I am not too well versed in bash.

Thanks for your time!

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
  • 1
    I'm not sure I would open a file called `randVid.exe` with a media player application... ;-) Apart from that, you should break your task down into its smallest parts, then tackle them individually. This way, you might be able to solve this yourself. If not, at least you'll be able to tell what *exactly* is giving you trouble, hence making your question somewhat more specific, maybe. – domsson Feb 20 '18 at 16:00
  • 1
    I'll give you some hints. You can break this down at least into two tasks: (1) Finding all the files in a given directory. (2) Creating a random number from within a defined range. Try searching for these here on SO, then combining them into a solution to your somewhat broader task. Check [this](https://stackoverflow.com/questions/10881157/read-file-names-from-directory-in-bash) and [that](https://stackoverflow.com/questions/2556190/random-number-from-a-range-in-a-bash-script) for starters? – domsson Feb 20 '18 at 16:04
  • @domsson Yes, the files are mp4 just forgot to change it haha. As for the second I understand the tasks I need to complete, it is just really a syntax thing since I couldn't really get it to work correctly. I looked up some examples, but some of them just didn't work on my terminal for some reason or I didn't understand it fully. – imVuLTz uMAD Feb 20 '18 at 18:37

1 Answers1

1

If you were on a GNU system, there is sort -R and shuf, but you're not.

I'd do this with bash: store the files in an array, find a random numeric index into the array, pull out the filename at that index.

files=( /Users/Me/Downloads/Stuff/* )
num=${#files[@]}
rand_idx=$(( RANDOM % num ))
rand_file=${files[rand_idx]}
echo "here's a random file: $rand_file"

going a step further, you can create a link to that randomly chosen file that has a "known" name:

ln -f "$rand_file" randomVideo

Then you can do

open -a "QuickTime Player" randomVideo
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks a lot. That was very helpful. Got it to work. Took out the creating a link to the file since it created issue but it work fine with just taking the path from rand_file and opening it directly – imVuLTz uMAD Feb 20 '18 at 18:36