语法错误:字词意外(预期为“ fi”)

时间:2018-10-23 13:00:58

标签: bash shell command-line scripting sh

我尝试执行脚本:

#!/bin/bash
cat test.txt
echo "Write del if you want delete or write save if you want save"
read s1
echo "Which symbol"
read s2
if [ $s1 = "del" ]
then
sed -i "/^$s2/d"
cat test.txt
if [ $s1 = "save" ]
then
echo "saved"
else
echo "Error"
fi cat test.txt

并且我输入-语法错误:单词意外(期望为“ fi”) 请帮忙!

2 个答案:

答案 0 :(得分:4)

if块或循环中缩进代码可以帮助捕获此类问题。每个if需要一个fi来结束该块。缩进代码:

#!/bin/bash
cat test.txt
echo "Write del if you want delete or write save if you want save"
read s1
echo "Which symbol"
read s2

if [ $s1 = "del" ]
then
    sed -i "/^$s2/d"
    cat test.txt

    if [ $s1 = "save" ]
    then
        echo "saved"
    else
        echo "Error"
    fi cat test.txt

您可以看到,初始块没有用其自己的fi关闭。此外,您还有一个catfi处于同一行上。那不应该在那里。而是这样的:

#!/bin/bash
cat test.txt
echo "Write del if you want delete or write save if you want save"
read s1
echo "Which symbol"
read s2

if [ $s1 = "del" ]
then
    sed -i "/^$s2/d"
    cat test.txt

    if [ $s1 = "save" ]
    then
        echo "saved"
    else
        echo "Error"
    fi 
    cat test.txt
fi

不能保证会做您想做的事,但这在语法上是正确的。

我会 HIGHLY 建议将其转储到shellcheck.net中,这样可以为您指明正确的方向。具体来说,您的测试中缺少双引号可能导致某些奇怪的行为。


基于@Aaron的评论,您可能正在寻找类似以下内容的东西:

#!/bin/bash
cat test.txt
echo "Write del if you want delete or write save if you want save"
read s1
echo "Which symbol"
read s2

if [ "$s1" = "del" ]; then
    sed -i "/^$s2/d" test.txt    
elif [ "$s1" = "save" ]; then
    echo "saved"
else
    echo "Error"
fi 

cat test.txt

答案 1 :(得分:2)

有几个问题。

首先,您必须替换以下行:

sed -i "/^$s2/d"
cat test.txt

作者

sed -i "/^$s2/d" test.txt

我猜您不想有2条if / then指令,而没有elsif指令,因此您应该像这样修复脚本:

then
sed -i "/^$s2/d" test.txt
elif [ $s1 = "save" ]
then
echo "saved"

此外,作为改进,我建议:

  • 将文件名放在专用变量中,以提高可读性和可维护性
  • 在脚本的开头触摸该文件,以确保该文件存在(即使为空)

最终,脚本将如下所示:

#!/bin/bash

filePath="test.txt"

[ ! -f "$filePath" ] && echo -e "ERROR: file $filePath not found. It is required for this script to work properly" >&2 && exit 1

cat "$filePath"
echo "Write del if you want delete or write save if you want save"
read s1
echo "Which symbol"
read s2

if [ "$s1" = "del" ]; then
  sed -i "/^$s2/d" "$filePath"
elif [ "$s1" = "save" ]; then
  echo "saved"
else
  echo "Error"
fi

cat "$filePath"

您可以看到'if'中引用了s1,以避免在出现空格字符时出现问题。