使用cat时为什么shell报告“命令未找到”?

时间:2018-03-09 03:42:50

标签: shell

我正在逐行处理文件,所以我的shell脚本是这样的:

check_vm_connectivity()
{
    $res=`cat temp.txt` # this is line 10
    i=0

    for line in "$res"
    do
        i=$i+1
        if [[ $i -gt 3 ]] ; then
            continue
        fi
        echo "${line}"
    done
}

temp.txt是这样的:

+--------------------------------------+
| ID                                   |
+--------------------------------------+
| cb91a52f-f0dd-443a-adfe-84c5c685d9b3 |
| 184564aa-9a7d-48ef-b8f0-ff9d51987e71 |
| f01f9739-c7a7-404c-8789-4e3e2edf314e |
| 825925cc-a816-4434-8b4b-a75301ddaefd |

当我运行脚本时,请报告:

vm_connectivity.sh: line 10: =+--------------------------------------+: command not found

为什么呢?如何解决这个错误?谢谢〜

2 个答案:

答案 0 :(得分:2)

我可以问你为什么要使用

$res=`cat temp.txt`? 

不应该

res=`cat temp.txt`

答案 1 :(得分:1)

shell中的

变量设置为var=而不是$var=

当您进入该功能时,

res为空,因此该行 扩展为空字符串,后跟等号, 接下来是temp.txt的内容。然后shell解释 那个,并且因为命令被换行符终止,并且 =+--------------------------------------+具有语法 一个命令,而不是其他任何东西,shell试图 像这样运行它。

您想:res=$(cat temp.txt)

然而,看起来你正试图输出 前三行,在这种情况下只是 做

head -n3 temp.txt

虽然从它的外观来看,你可能想要除前三个以外的所有 行:

tail -n +4 temp.txt

如果你正在寻找uuids:

tail -n +4 temp.txt | awk '{print $2}'
相关问题