Linux 从 bash 脚本中提取值

Linux extract values from bash scipt

我正在尝试编写一个 bash 脚本,但是有一个问题 - 我无法在 do-done 之外看到变量的内容。有帮助吗?

#!/bin/bash

file="ip.txt"

while IFS=: read -r f1 f2 f3
do
     printf '%s %s %s\n' "$f1" "$f2" "$f3"
done <"$file"

printf '%s %s %s\n' "$f1" "$f2" "$f3"

echo -e "iptables -t nat -A PREROUTING -p tcp --dport $f2 -j DNAT --to-destination $f1:$f3"

输出>

192.168.0.1  
2000  
1000  

iptables -t nat -A PREROUTING -p tcp --dport  -j DNAT --to-destination :

你的文件末尾有一个空行,因此 $f1 $f2 $f3 在循环的最后一次迭代时变为空,这不是问题吗?

它的已知 bash 行为。阅读此处,了解为什么以及如何避免:http://mywiki.wooledge.org/BashPitfalls#grep_foo_bar_.7C_while_read_- or http://mywiki.wooledge.org/BashFAQ/024

我可以看到你的问题

while IFS=: read -r f1 f2 f3
do
     printf 'Loop: %s %s %s\n' "$f1" "$f2" "$f3"
done <<< "192.168.0.1:2000:1000"
printf 'After: %s %s %s\n' "$f1" "$f2" "$f3"

您构建了一个结构,您可以在其中使用在循环中设置的变量,但不能使用通过读取设置的变量。 您可以使用

while IFS=: read -r xf1 xf2 xf3
do
     printf 'Loop: %s %s %s\n' "$xf1" "$xf2" "$xf3"
     f1=$xf1
     f2=$xf2
     f3=$xf3
done <<< "192.168.0.1:2000:1000"
printf 'After: %s %s %s\n' "$f1" "$f2" "$f3"

我猜你不想使用这个,所以请阅读循环内的行:

while read -r line
do
     IFS=: read -r f1 f2 f3 <<< "${line}"
     printf 'Loop: %s %s %s\n' "$f1" "$f2" "$f3"
done <<< "192.168.0.1:2000:1000"
printf 'After: %s %s %s\n' "$f1" "$f2" "$f3"