为什么这个简单的 bash 脚本会在 if/then/else 上抛出错误?

the*_*fog 1 shell bash

如果我尝试运行此脚本:

clear
echo -n "please enter a value"

read num 

if [ "$num" -eq 8 ] then
        echo "you entered 8"
else
        echo "the number you entered was not 8"
Run Code Online (Sandbox Code Playgroud)

我得到以下输出/错误:

请输入一个值 5
./script.sh: line 9: 意外标记“else”附近的语法错误
./script.sh: line 9: else'

为什么这个脚本不能运行?

roa*_*ima 6

您在if子句之后缺少分号或换行符,并且块的fi末尾没有if

#!/bin/bash
clear
echo -n "please enter a value"

read num 

if [ "$num" -eq 8 ]
then
        echo "you entered 8"
else
        echo "the number you entered was not 8"
fi
Run Code Online (Sandbox Code Playgroud)

其他一些建议:

  • 脚本应该总是以#!一行开始告诉系统使用哪个解释器
  • 您的比较[ "$num" -eq 8 ]是数字比较。如果您不确定用户是否真的会输入数字,请考虑使用字符串比较,[ 8 = "$num" ]
  • 您可以将提示包装到read语句中,read -p "Please enter a value: " num