Failed to get command return value in script

I have the following script:

        serverip=$1
        key=$2
        linenumber=0
        ##CHeck If server IP exists
        if grep -wq $serverip server; then
                echo "IP exists"
                linenumber=`awk '$0 ~ "$serverip" {print NR}' file`
                echo "$linenumber"
        fi

The file contains:

192.168.18.2       testing123      3

./radius_adt.sh 192.168.18.2 nevis

Does not print line number.

The awk command works outside the script.

awk '$0 ~ "192.168.18.4" {print NR}' file

output: 1

Why doesn’t the command run inside the script and its return value is copied to linenumber.

+4
source share
1 answer

This line is the problem:

linenumber=`awk '$0 ~ "$serverip" {print NR}' file`

And shellit will not be able to expand $serveripinside single quotes, and awk will process it literally. You should use it in such a way that you pass the awk shell variable:

linenumber=$(awk -v serverip="$serverip" '$0 ~ serverip {print NR}' file)
+3
source

Source: https://habr.com/ru/post/1610936/


All Articles