简体   繁体   English

不确定如何正确使用变量并在 bash 脚本的 if 语句中使用它们

[英]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.我正在努力思考如何在 bash 脚本中正确声明变量以及如何在我的程序中进一步使用它们。 What I wish to accomplish is to store the IP address of a blocked IP in a variable.我希望完成的是将被阻止 IP 的 IP 地址存储在一个变量中。 I wish to use iptables -S INPUT [line number] to do this.我希望使用 iptables -S INPUT [line number] 来做到这一点。 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.此外,我希望检查这个 IP 地址是否与另一个 IP 地址相同,然后继续将 iptables 策略更改为 ACCEPT,如果它确实是相同的地址。

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.我遇到的问题是我对 bash 脚本编写的经验太少了,我完全不确定为什么我的脚本不起作用,或者我可以改变什么来使它工作。

Hoping for any experienced shell scripters there who could help me :)希望那里有任何经验丰富的 shell 脚本编写者可以帮助我:)


#!/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.您的语法总体上看起来不错,但是您是否不需要为每个变量赋值使用$(echo ... ) For example, these are sufficient to assign IP_ADDRESS and IPSTATUS_LINE_NUMBER,例如,这些足以分配 IP_ADDRESS 和 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,在发生错误的那一行,尝试在命令替换中调用iptables ,而不是回显命令和 args,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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