0

I'm attempting to write a script in bash that will automatically add a line/replace a line in /etc/rsyslog.conf when the network Gateway changes. This would enable distribution of an rsyslog server with directed logging to specific log file.

I haven't been able to determine why this fails and hoping someone with a better understanding can address.

The following is the script.

#!/bin/bash
GETGATEWAY="route -n | grep 'UG[ \t]' | awk '{print \$2}'"
echo "This is a test"
echo $GETGATEWAY
shopt -s extglob
$GETGATEWAY

Result follows.

This is a test route -n | grep 'UG[ \t]' | awk '{print $2}' Usage: route [-nNvee] [-FC] [] List kernel routing tables route [-v] [-FC] {add|del|flush} ... Modify routing table for AF.

   route {-h|--help} [<AF>]              Detailed usage syntax for specified AF.
   route {-V|--version}                  Display version/author and exit.

    -v, --verbose            be verbose
    -n, --numeric            don't resolve names
    -e, --extend             display other/more information
    -F, --fib                display Forwarding Information Base (default)
    -C, --cache              display routing cache instead of FIB

=Use '-A ' or '--'; default: inet List of possible address families (which support routing): inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25) netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP) x25 (CCITT X.25)

If you copy the echo line after "This is a test" and paste on the terminal to execute, it works as expected. route -n | grep 'UG[ \t]' | awk '{print $2}'

I've tried multiple shell options with and without shopt -s extglob.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Rsyslogn
  • 3
  • 1
  • Needless use of an extra _pipe_ and `grep` when `route -n | awk '/UG[ \t]/{print $2}'` produces the same results as `route -n | grep 'UG[ \t]' | awk '{print $2}'` does! – user3439894 Feb 21 '17 at 05:06

2 Answers2

0

I am not sure why you are storing the command sequence in a variable and then trying to execute it through an evaluation ($var). You could do this:

eval "$GETGATEWAY"

Without eval, shell interprets route as the command and everything else, including | etc., as arguments to it. And extglob option has nothing to do with this.

You may want to take a look at this post:

Why should eval be avoided in Bash, and what should I use instead?

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
0

you should use command substitution for computing the IP address and storing it to any variable.

var=$(command1|command2|....)

Example:

GATEWAY=$(route -n |awk '/UG/{print $2}')
echo $GATEWAY
10.1.1.1
P....
  • 17,421
  • 2
  • 32
  • 52