Home > Enterprise >  Concatenate String from inside an Array to another String in Bash
Concatenate String from inside an Array to another String in Bash

Time:12-21

I have different .ovpn files with vpn configurations. I wrote a script, that checks the load of available servers and trys to connect with the one with the least load. My problem is that the string variables who describe the Connection NetworkManager will choose, are not recognized by nmcli when they are called from an array within a script.

I concatenate and connect in this way in the script:

top="${TOP_TEN[$iters]}.tcp"
nmcli con up $top --ask

Here nmcli throws an unknown connection error. I tried echoing the $top variable before and tried to connect manually which works just fine. The variable in this example is "bg52.nordvpn.com.tcp".

Then i wrote another 4 liner to see if my concatenation messes something up:

TOP_TEN=(vpn1 vpn2 bg52.nordvpn.com vpn4)
echo ${TOP_TEN[2]}.tcp
top="${TOP_TEN[2]}.tcp"
nmcli con up $top --ask

Also here it also works just fine.

Does anybody understand why my ovpn connection is not recognized when passed as a string from a bash array?

Here is the complete script if it helps you better to understand the problem.

#!/usr/bin/bash

OVPN_FILES="/usr/lib/python3.10/site-packages/openpyn/files/ovpn_tcp"
COUNTRY_CODE=$1
TOP_TEN=()

function get_top_servers() {
    TOP_TEN=()
    while IFS= read -r server; do
        TOP_TEN =( $server )
    done < <( nordvpn-server-find -n 10 -l $1 | tail -n 10 | tr -s " " | cut -d\  -f 1 )
}

function get_rand_ccode() {
    rand_countr_code=`ls $OVPN_FILES | cut -c1-2 | uniq | shuf | head -n 1`
}

function old_con_down() {
    ACTIVE_VPN=`nmcli c show --active | grep vpn | tr -s " " | cut -d\  -f 2`
    if [ ! -z "$ACTIVE_VPN" ]; then
        echo "Found active connection. Deactivating $ACTIVE_VPN ... "
        nmcli con down $ACTIVE_VPN
        # sleep 3
    fi
}

if [ -z "$COUNTRY_CODE" ]; then
    echo "set ccode"
    COUNTRY_CODE=$(get_rand_ccode)
fi

echo "Get Top Servers for $COUNTRY_CODE"
get_top_servers $COUNTRY_CODE

iters=0

while [ 1 ]
do  
    if (( $iters > 9 )); then
        COUNTRY_CODE=$(get_rand_ccode)
        get_top_servers $COUNTRY_CODE
        iters=0
    fi

    old_con_down
    echo "Fastest Server is ..."
    top="${TOP_TEN[$iters]}.tcp"
    echo "${TOP_TEN[@]}"
    nmcli con up $top --ask
    if [ -z $? ]; then
        exit 1
    else
        ((iters  )) 
    fi
done

CodePudding user response:

The nordvpn-server-find i'm using inside the script was echoing also Control Sequences for bold and colored fonts. I had to strip them of, before feeding the output into nmcli.

  • Related