0

In a bash script I am starting openvpn as a client like this:

#!/bin/bash
conf_file=/etc/openvpn/blahblah.conf
openvpn_pid_file="/var/run/openvpn-client/ovpnc.pid"
command_line="/usr/bin/openvpn --config $conf_file --daemon"
$command_line
openvpn_pid=$!
echo "openvpn_pid=$openvpn_pid"
echo $openvpn_pid >> "$openvpn_pid_file"

After a successful start of openvpn, my variable openvpn_pid is empty and my openvpn_pid_file is empty. However, pgrep openvpn will give me the PID. Why am I not getting that PID in my script? What should I change in order to get the correct PID in my variable and ultimately into the openvpn_pid_file?

This is all on Arch Linux.

MountainX
  • 681
  • 3
  • 12
  • 25
  • 3
    Isn't `openvpn --writepid ` working? – Sven Sep 05 '18 at 19:14
  • @Sven I was not aware of that. Thanks. Yes, that method works. Is that the only method that will work or can I also use a variation of the general purpose methods I showed in my question? – MountainX Sep 05 '18 at 20:45

1 Answers1

1

From man bash:

   !      Expands  to  the  process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg              builtin

In other words: $! only contains a value if the process is backgrounded. Because you did not background a process from the shell, $! is empty, and therefore, openvpn_pid is empty.

As for the solution, it's in Sven's comment.

As for

Ljm Dullaart
  • 151
  • 4