1

So, I wrote this crap bash script that connects randomly to a vpn server from a pool of 100+ ovpn config files:

test {

_OVPNs="/path/to/OVPNs"
_RANDOM=$(shuf -e 1 -n 1 ${_OVPNs}/*)

    sudo openvpn --config ${_RANDOM}
}

It works fine most of the time but occasionally produces weird errors:

sudo openvpn --config 1

or

Options error: In [CMD-LINE]:1: Error opening configuration file: 1
Use --help for more information.

Any idea why "1" is occasionally assigned as the result of the shuffle?

2

You are getting 1 as the output as one of the inputs to shuf for shuffling around is 1 (-e 1 ...).

You need to pass all the possible elements, by using an array:

_ovpns=( /path/to/OVPNs/* )
shuf -e "${ovpns[@]}" -n 1 

or directly do:

shuf -e /path/to/OVPNs/* -n 1

Taking the directory name as a variable:

_ovpns='/path/to/OVPNs'
shuf -e "${_ovpns}"/* -n 1

Note that, unless absolutely necessary do not use all uppercases (with underscore) as user defined variable name to avoid potential overwriting of environment variables.

  • I don't think you always get 1; at least as tested with coreutils 8.25, it appears to treat all non-option arguments after the -e as elements to shuffle i.e. 1 just becomes one of the outputs. – steeldriver Dec 26 '16 at 3:44
  • @steeldriver You are right. I stand corrected. Thanks. – heemayl Dec 26 '16 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.