user9781389
user9781389

Reputation:

How can I output a files random selection to a new command

I'm trying to practice some coding and I am trying to make OpenVPN pick a random OVPN file for my Qubes OS laptop, and eventually for my Pop!_OS one. How do I output the commands from pick.sh into openvpn correctly e.g.

openvpn --config (result from pick.sh)

the Pick.sh is as such

#!/bin/bash
# Reads a given directory and picks a random file.

# The directory you want to use. You could use "$1" instead if you
# wanted to parametrize it.
#DIR="./openvpn"
# DIR="$1"

# Internal Field Separator set to newline, so file names with
# spaces do not break our script.
IFS='
'

if [[ -d "${DIR}" ]]
then
  # Runs ls on the given dir, and dumps the output into a matrix,
  # it uses the new lines character as a field delimiter, as explained above.
  file_matrix=($(ls "${DIR}"))
  num_files=${#file_matrix[*]}
  # This is the command you want to run on a random file.
  # Change "ls -l" by anything you want, it's just an example.
  ls --file-type ovpn "${DIR}/${file_matrix[$((RANDOM%num_files))]}"
fi

exit 0

Upvotes: 0

Views: 72

Answers (1)

Brandon
Brandon

Reputation: 11

If you want to select a random file in a directory, just do:

ls -1 | sort -R | head -1

This will:

  1. list all the files in current directory as a column
  2. scramble the list (i.e. sort it randomly)
  3. select the first item in the list

-

So to put it together you could do something like this:

openvpn --config `ls -1 | sort -R | head -1`

This will run as a one-liner so you can type it directly into the terminal, or you could just have this line in your bash script.

Upvotes: 1

Related Questions