I am writing a small script that would choose random file for me from the directory and execute command with this chosen filename as a parameter.

It is about choosing random .ovpn file and run sudo openvpn path_to_filename

Here is my script:
echo ${#allFilesInDirectory[@]}
randomNumber=$[RANDOM % ${#allFilesInDirectory[@]}]
echo $randomNumber
echo ${allFilesInDirectory[randomNumber]}
echo $choosenFile
echo "CHOOSEN: ${choosenFile} AS A RANDOM WITH NUMBER ${randomNumber} OF ${#allFilesInDirectory[@]} "
echo ""

First of all at the echo starting with CHOOSEN there is no path displayed (so no content of choosenFile variable is passed), but a randomNumber variable content is displayed! I tried to play with ' " \ and some other syntaxes with no success.

The more important is that execution of my command doesn't see the content of variable choosenFile too! I tried to do for few ways too. Like for example

command="sudo openvpn ${choosenFile}"
eval $command

"sudo openvpn ${choosenFIle}"

"sudo openvpn \${choosenFIle}"

"sudo openvpn $choosenFIle"

and at best I got openvpn help output, so no content of variable choosenFile was passed.

May someone point my lack of knowledge? I just started with bash scripts.

closed as off-topic by Kusalananda May 11 at 11:07

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Kusalananda
If this question can be reworded to fit the rules in the help center, please edit the question.


You have a typo in the variable name.



Should be:


Actually, for good practice you should double-quote your variables when you use them. This is so that spaces in the values don't get evaluated by the shell when you least expect it. So the correct line should be this:


I would strongly recommend you use https://www.shellcheck.net/ for checking your shell scripts. As it happens it would have picked up your typo and warned you about it.

As for the second part of your question, just stop double-quoting the entire line. Write the command and reference the variable where you need it, for example like this:

sudo openvpn "$choosenFile"
  • Thank a lot! That is wonderful. And one more time thanks you for the link and double-qoute hint. Have a nice day ! – zabehe May 11 at 10:57

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