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

时间:2018-05-12 16:39:04

标签: bash

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

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

Pick.sh就是这样

{{1}}

1 个答案:

答案 0 :(得分:1)

如果要在目录中选择随机文件,只需执行:

ls -1 | sort -R | head -1

这将:

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

    所以把它放在一起就可以做到这样的事情:

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

    这将作为单行运行,因此您可以直接在终端中输入,或者您可以在bash脚本中使用此行。