Search code examples
perlvpnone-linermpv

How do I expand on this one line Perl script to run a command until specific KEYWORD in output, then also play a sound?


I have a problem with my NordVPN account where I have to sometimes run the client upwards of 10 times, with their terrible CLI tool, until it finally successfully chooses a server that accepts my login.

I came across an old post here which I adapted to suit my needs, and it looks like this currently:

perl -e 'do { sleep(7); $_ = `nordvpn connect`; print $_; } until (m/connected/);'

It keeps running connect until it observes the word "connected" hopefully in the output. But I want to expand this one step further. When it successfully gets the keyword in the output, I want it then to 'mpv success.wav' or some similar thing, to play a simple .wav file located in the same directory. mpv works great for this.

Thanks very much in advance!


Solution

  • That loop quits when the condition is met so just add desired action(s) after the loop is done

    perl -we'do { sleep(7); $_ = `nordvpn connect`; print $_; } 
        until (/connected/); system("mpv success.wav")'
    

    This prints to screen whatever mpv does, what can be avoided for example by changing to

    system("mpv success.wav > /dev/null 2>&1")
    

    Here the STDOUT stream is redirected to the null device (/dev/null) and then STDERR stream (file descriptor 2) is redirected to STDOUT (fd 1). So it all goes to the void.

    Also, one can turn it around

    perl -we'while (sleep 7) { 
        if (`nordvpn connect` =~ /connected/) { system("mpv success.wav"); last } }'
    

    While this isn't as concise it is far more flexible for further changes. It does not print the command's return, as the original does. That is easily added if it is really wanted.