Find the answer to your Linux question:
Results 1 to 3 of 3
So, I'm currently writing a script for IP addresses and what not. Currently it looks like this: Code: #!/bin/bash echo -n "Enter Network: " read IP; for i in `seq ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jul 2009
    Posts
    24

    for i in `seq 1 4` issue


    So, I'm currently writing a script for IP addresses and what not.

    Currently it looks like this:

    Code:
    #!/bin/bash
    echo -n "Enter Network: "
    read IP;
    
    for i in `seq 1 4`
    do
    
    GATEWAY=$(echo $IP | awk -F "." '{print $1 "." $2 "." $3 "." ($4+$i+2)}')
    
    done
    
    echo $GATEWAY;
    Very very basic.. However, this is what happens:

    Code:
    # ./usable
    # Enter Network: 127.0.0.1
    127.0.0.130
    Why does it return .130?

  2. #2
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    I can't tell you exactly why, but it is because there is no such variable as $i. Remember, the code that awk is executing is awk code, but you have defined i as a Bash variable. Bash variables and awk variables are completely different.

    The first thing to be aware of is that the loop in your program does nothing. Your problem would operate the same if you wrote:
    Code:
    #!/bin/bash
    echo -n "Enter Network: "
    read IP;
    
    GATEWAY=$(echo $IP | awk -F "." '{print $1 "." $2 "." $3 "." ($4+4+2)}')
    
    echo $GATEWAY
    In your loop, you just overwrite GATEWAY, so only the last value is remembered.

    In any case, if you actually did want to use a loop, you can turn a Bash variable into an awk variable by doing:
    Code:
    #!/bin/bash
    echo -n "Enter Network: "
    read IP;
    
    for i in `seq 1 4`
    do
    
    GATEWAY=$(echo $IP | awk -v i="$i" -F "." '{print $1 "." $2 "." $3 "." ($4+i+2)}')
    
    done
    
    echo $GATEWAY
    Note the -v i="$i" bit. This assigns the Bash variable $i to the awk variable i. Don't use $i for awk variables: $ variables are always fields in awk, and you just want the variable (if i was defined as 4, for instance, $i would return the fourth field of the line of input, while i would return the number 4).

    Does this make sense? I ran it as follows and it worked:
    Code:
    $ for i in $(seq 1 4); do echo '127.0.0.1' | awk -v i=$i -F. '{print $1 "." $2 "." $3 "." ($4+i+2)}'; done
    127.0.0.4
    127.0.0.5
    127.0.0.6
    127.0.0.7

  3. #3
    Just Joined!
    Join Date
    Jul 2009
    Posts
    24
    IT workeD!! Thanks so much!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •