如何将文件随机选择输出到新命令



我正在尝试练习一些编码,我试图让OpenVPN为我的Qubes OS笔记本电脑选择一个随机的OVPN文件,最终为我的Pop!_OS一个。如何将命令从 pick.sh 正确输出到 openvpn 例如

openvpn --config (result from pick.sh)

Pick.sh 就是这样

#!/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

如果你想在目录中选择一个随机文件,只需做:

ls -1 | sort -R | head -1

这将:

  1. 将当前目录中的所有文件列为一列
  2. 打乱列表(即随机排序(
  3. 选择列表中的第一项

-

所以要把它放在一起,你可以做这样的事情:

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

这将作为单行运行,因此您可以直接在终端中键入它,或者您可以在 bash 脚本中只包含此行。

最新更新