0

I'm having some trouble formatting the first line in this bash script I'm trying to work on, which is supposed to look for a #Server line in a file and then print $newip on the line below it.

Ideally, I want the $newip to look something like this:

route 74.125.141.102 255.255.255.255 net_gateway

But when I try to run the script, something is going wrong, because all I get is this:

awk: fatal: cannot open file `255.255.255.255' for reading (No such file or directory)

Here is my full bash script:

newip="route $(dig google.com +short | (head -n1 && tail -n1)) 255.255.255.255 net_gateway"
awk -v newip=$newip '{
  if($1 == "#Server"){
    l = NR;
    print $0
  }
  else if(l>0 && NR == l+1){
    print $newip
  }
  else if(l==0 || NR != l+2){
    print $0
  }
}' serverip > serverip.tmp

mv -f serverip.tmp serverip

(By the way, if your wondering what this script is for, it will eventually be used to add an exception for a certain website for my OpenVpn config)

I know it is something stupid like adding an extra set of quotes or parenthesis in the first line, but I can't figure out what to do.

user97462
  • 35
  • 7
  • 1
    Never use a variable named `l` as it looks far too much like the number `1` which obfuscates your code. **Always** quote shell variables unless you fully understand all of the implications of not doing so and have a specific purpose in mind. – Ed Morton May 30 '16 at 03:37

1 Answers1

1

You'll need to put double quotes around the reference to newip in the awk command line:

awk -v newip="$newip" '{ … }' serverip > serverip.tmp

Now newip is a 4-word variable value in the awk script, which can be printed as you show.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278