我尝试执行脚本:
#!/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”) 请帮忙!
答案 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
关闭。此外,您还有一个cat
与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
不能保证会做您想做的事,但这在语法上是正确的。
我会 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,以避免在出现空格字符时出现问题。