![Shell 脚本的循环出现意外行为](https://linux22.com/image/603040/Shell%20%E8%84%9A%E6%9C%AC%E7%9A%84%E5%BE%AA%E7%8E%AF%E5%87%BA%E7%8E%B0%E6%84%8F%E5%A4%96%E8%A1%8C%E4%B8%BA.png)
Shell 脚本 for 循环的行为出乎意料!要求逐行迭代属性文件的循环。必须使用 for 循环。
hostnamefl=/tmp/propperty.txt
for property in $(cat $hostnamefl)
do
hostname=`echo $property | awk '{print $1}'`
echo $hostname
user=`echo $property | awk '{print $2}'`
echo $user
pas=`echo $property | awk '{print $3}'`
echo $pas
echo "---------------------------------------------------------------------------------"
done
属性.txt
host1 host1user host1pas
host2 host2user host2pas
host3 host3user host3pas
我得到的结果如下:
host1
---------------------------------------------------------------------------------
host1user
---------------------------------------------------------------------------------
host1pas
---------------------------------------------------------------------------------
host2
---------------------------------------------------------------------------------
host2user
---------------------------------------------------------------------------------
host2pas
---------------------------------------------------------------------------------
host3
---------------------------------------------------------------------------------
host3user
---------------------------------------------------------------------------------
host3pas
---------------------------------------------------------------------------------
预期结果:
host1
host1user
host1pas
---------------------------------------------------------------------------------
host2
host2user
host2pas
---------------------------------------------------------------------------------
host3
host3user
host3pas
---------------------------------------------------------------------------------
For 循环是逐字迭代而不是逐行迭代,我该如何解决它?
答案1
这就是for
循环的工作方式——它们将所有输入视为以空格分隔的单词。您需要的是read
内置命令,它一次读取一行。
while read line ; do
for word in $line; do
echo $word
done
echo ---------------------------------------------------------------------------------
done < /tmp/propperty.txt
答案2
如果cat /tmp/propperty.txt
输出设置 IFS 变量可能会有帮助
host1 host1user host1pas
host2 host2user host2pas
host3 host3user host3pas
请参阅 bash 手册页中的特殊参数
IFS=:
hostnamefl=/tmp/propperty.txt
for property in $(cat $hostnamefl)
do
hostname=`echo $property | awk '{print $1}'`
echo $hostname
user=`echo $property | awk '{print $2}'`
echo $user
pas=`echo $property | awk '{print $3}'`
echo $pas
echo "---------------------------------------------------------------------------------"
done
答案3
如果 rhasti 的答案对你不起作用。你可以这样做
while read property
do
hostname=`echo $property | awk '{print $1}'`
echo $hostname
user=`echo $property | awk '{print $2}'`
echo $user
pas=`echo $property | awk '{print $3}'`
echo $pas
echo "---------------------------------------------------------------------------------"
done < /tmp/propperty.txt
答案4
read 可以为你解析该行:不需要 awk
while read hostname user pas
do
echo $hostname
echo $user
echo $pas
echo -------------
done < /tmp/property.txt