简体   繁体   中英

Not sure how to properly use variables and use them in if statements in bash scripting

I'm struggling to wrap my head around how to properly declare variables in bash scripting and how to use them further on in my program. What I wish to accomplish is to store the IP address of a blocked IP in a variable. I wish to use iptables -S INPUT [line number] to do this. Furthermore I wish to check if this IP address i identical too another IP address to then go ahead and change the iptables policy to ACCEPT if it is indeed the same address.

The problem that I am having is that I have such little experience with bash scripting that I am not really sure at all why my script doesn't work or what I can change to make it work.

Hoping for any experienced shell scripters there who could help me :)


#!/bin/bash

# Getting an IP address from a saved database
IP_ADDRESS=$(echo "${line%%,*}")

# Defining the line number for iptables -L INPUT --line-numbers while reading list
LINE_NUMBER=$(echo "$iptables_line" | cut -d " " -f1)

IPSTATUS_LINE_NUMBER=$(echo "$LINE_NUMBER")

# Wanting to store the IP address from iptables -S INPUT here to use for later
LINE_FROM_IPSTATUS=$(echo "iptables -S INPUT $IPSTATUS_LINE_NUMBER" | grep "[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+")   ############### Error is here
                
echo "IP imported from iptables -S => $LINE_FROM_IPSTATUS"

# Check if the IP address is on the iptables -S line
    if [ "$LINE_FROM_IPSTATUS" = "$IP_ADDRESS" ]; then ### Potential second error here

        echo "IP: $IP_ADDRESS was located on line nr. $LINE_NUMBER"
        
        # Changing the rule in INPUT Chain to ACCEPT
        iptables -R INPUT "$LINE_NUMBER" -s "$IP_ADDRESS" -j ACCEPT
    else
        # Echo if something went wrong
        echo "Oops. Something went wrong"
    fi


Your syntax looks good overall, but don't you don't need to use $(echo ... ) for every variable assignment. For example, these are sufficient to assign IP_ADDRESS and IPSTATUS_LINE_NUMBER,

IP_ADDRESS="${line%%,*}"

IPSTATUS_LINE_NUMBER="$LINE_NUMBER"

On the line where your error is happening, try calling iptables inside the command substitution instead of echo-ing the command and args,

LINE_FROM_IPSTATUS=$(iptables -S INPUT $IPSTATUS_LINE_NUMBER | grep "[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM