如何解决Bash错误"syntax error near unexpected token"?

How to solve the Bash error "syntax error near unexpected token"?

我在 CentOS 中收到一条错误消息说

'line 7: syntax error near unexpected token `then' and 'syntax error: unexpected end of file'

此代码的要点是要求用户提供文件名,然后根据他们选择的内容复制移动或​​删除文件。

echo "Please enter the file name you wish to alter: "
read filename

if [ -f $filename ]; then
echo "Please enter either C, M, or D to copy, move or delete the file: "
read op
        if [ "$op" = "C" ] || [ "$op" = "c" ]; then
echo "Please enter the destination directory in which you wish to copy to$
read dest
cp $filename $dest/$filename
echo "Complete"

elif [ "$op" = "M"] || [ "$op" = "m" ]; then
echo "Please enter the destination directory in which you wish to move to$
read dest
mv $filename $dest/$filename
echo "Complete"

elif [ "$op" = "D"] || [ "$op" = "d" ]; then
rm -i $filename
echo "Complete"

else "$filename does not exists try again."

fi

第三个 echo 命令有一个未终止的字符串文字:

echo "Please enter the destination directory in which you wish to copy to$

也许您想这样写:

echo "Please enter the destination directory in which you wish to copy to:"

第五条echo命令也有同样的问题

此外,此声明无效:

else "$filename does not exists try again."

也许您想这样写:

else
    echo "$filename does not exists try again."

另外,没有fi对应第一个if语句。

此外,语法 [ "$op" = "M"] 无效。 ] 字符前必须有一个 space,例如:[ "$op" = "M" ].

您在 [ "$op" = "D"] 中再次遇到同样的问题。

在第 7 行,您关闭括号的速度太快了:
而不是:

if [ "$op" = "C"]  ||  ["$op" = "c" ]; then

你应该有:

if [ "$op" = "C"  ||  "$op" = "c" ]; then