Shell 脚本的循环出现意外行为

Shell 脚本的循环出现意外行为

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

相关内容