user97462 user97462 - 4 months ago 5x
Bash Question

Bash Variable Syntax Issue

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 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 `' for reading (No such file or directory)

Here is my full bash script:

newip="route $(dig +short | (head -n1 && tail -n1)) 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.


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.