在while循环中不记住修改变量

时间:2015-11-07 17:56:23

标签: bash shell while-loop

我试着询问人们在iptables上使用哪个接口作为公共接口: while-loop接缝不记得变量,我真的不知道为什么。

  #!/bin/sh
### Show all available interfaces and configure to use them in while-loop:
# Here is the answer of the function: 
# "${PUB_IF}" != "eth0" -a "${PUB_IF}" != "eth1" -a "${PUB_IF}" != "vmbr0"
function good_interfaces() {
ip a | grep '^[0-9]:' | grep -v 'lo' | awk '{ print $2 }' | sed -e 's/^/"/' -e 's/:$/"/' -e '/$/ i\-a "${PUB_IF}" !=' | sed '$!N; s/\n/ /g' | tr '\n' ' ' | awk 'sub("^...", "")'
}

### Show available interfaces
# Here is the answer of "echo ${IF_LIST}"
# eth0? eth1? vmbr0?
IF_LIST=$(ip a | grep '^[0-9]:' | grep -v 'lo' | awk '{ print $2 }' | sed 's/:/\?/g' | tr '\n' ' ')

while [ $(good_interfaces) ]; do
# When i replace $(good_interfaces) by its answer, the loop works: 
# while [ "${PUB_IF}" != "eth0" -a "${PUB_IF}" != "eth1" -a "${PUB_IF}" != "vmbr0" ] --> without the variable it works but isn't personalized for all machines
  echo "${IF_LIST}"
  read -p "Enter the interface to use: " PUB_IF
done;

以下是ip a答案:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master vmbr0 state UP group default qlen 1000
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet x.x.x.x/x brd x.x.x.x scope global eth0
       valid_lft forever preferred_lft forever
3: eth1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN group default qlen 1000
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff

1 个答案:

答案 0 :(得分:0)

首先对您的代码发表一些评论:

  • #!/bin/sh
    删除此行上的空格(并使用bash)。现在该行只是评论
  • ip a | grep '^[0-9]:' | grep -v 'lo' | a lot more
    对不起,命令变得复杂了。当你没有看到输入时,你认为你可以在两个月内自己理解吗?
  • IF_LIST=$(ip a | grep '^[0-9]:' | grep -v 'lo' | and more)
    一些代码与函数good_interfaces
  • 共享
  • while [ $(good_interfaces) ]; do
    while循环需要一个true / false表达式,您希望函数返回的字符串将被视为表达式。

那么你应该如何实现一个用于读取PUB_IF并在有效时断开的构造?

将所有有效接口放在带有明确分隔符的字符串中(我将使用空格)。 我将在字符串前后添加一个空格,以便以后轻松匹配 要求PUB_IF并检查。

valid_interfaces=" eth0 eth1 vmbr0 "
PUB_IF=""
# Edit: changed "while [ true ]; do" into "while true; do"
while true; do
   read -p "Enter the interface to use: " PUB_IF
   if [[ "${valid_interfaces}" = *;${PUB_IF};* ]]; then
      echo "${PUB_IF} is valid"
      break
   else
      echo "Nope, please enter something like${valid_interfaces}"
   fi
done 

另一个问题是如何找到有效的接口。使用剪切:

valid_interfaces=" $(ip a | grep ": <" | grep -v "lo" | cut -d: -f2 | tr '\n' ' ')