我試着問人們哪些接口用作iptables上的公共接口: while循環接縫不記住變量,我真的不知道爲什麼。在while循環中不記住修改變量
#!/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
請參閱http://stackoverflow.com/help/mcve – Jubobs
序列'grep ... | grep -v ... | awk ... | sed ...'應該是單個命令 - 可能是'awk',但是現在你可以使用'sed'或'grep'來代替。無論如何,連續的四個命令都不需要。即使沒有這些,你也可以把序列放到一個函數中,這樣你就不必重複自己。這會讓我們有機會理解你的問題。我假設'未設置的PIB_IF'在原始代碼中不存在。如果是,'-z「$ {PUB_IF}」'測試是多餘的 - 它是未設置的,因此總是計爲零長度。 –
在循環後不記住的循環中設置變量的正常原因是循環在子外殼中運行。這並不是顯而易見的問題。你可以在'ip a'中顯示三行或四行輸出 - 一個用於'lo'界面,至少另外兩個輸出,這樣我們那些沒有在他們機器上使用'ip'命令的人可以看到你正在處理的數據是什麼樣子的喜歡? –