2

运行shell脚本提示“语法错误: 未预期的文件结尾”

 1 year ago
source link: https://blog.51cto.com/u_14045290/5811316
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

运行shell脚本提示“语法错误: 未预期的文件结尾”

推荐 原创

shenshushu 2022-10-31 21:36:10 博主文章分类:shell ©著作权

文章标签 shell脚本 文章分类 Linux 系统/运维 阅读数232

当时正在写一个小需求,shell脚本实现的功能是:通过 read 读入变量实现加减剩除等,而且要判断一个输入的2个变量是否为空,为空值则退出。输入的变量不是数字则退出。

自己编写的代码如下

#! /bin/bash
read -p "Ple input two num:" a b
if [ ${ #a } -le 0 ] && {
echo "this first number is null"
exit 1
}
if [ ${ #b } -le 0 ] && {
echo "this second number is null"
exit 1
}

expr $a +2 &>/dev/null
revecd_A=$?
expr $b +3 &>/dev/null
revecd_B=$?
if [ $revecd_A -ne 0 -o $revecd_B -ne 0 ];then
echo "ple input two number"
exit 1
fi

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a/b=$(($a/$b))"
echo "a%b=$(($a%$b))"
echo "a**b=$(($a**$b))"

然后运行的时候提示错误

运行shell脚本提示“语法错误: 未预期的文件结尾”_shell脚本

后来检查发现多了if

运行shell脚本提示“语法错误: 未预期的文件结尾”_shell脚本_02

修改正确后代码如下

#! /bin/bash
read -p "Ple input two num:" a b
[ ${#a} -le 0 ] && {
echo "this first number is null"
exit 1
}
[ ${#b} -le 0 ] && {
echo "this second number is null"
exit 1
}

expr $a + 1 &>/dev/null
revecd_A=$?
expr $b + 1 &>/dev/null
revecd_B=$?
if [ $revecd_A -ne 0 -o $revecd_B -ne 0 ];then
echo "not unmber,ple input again"
exit 1
fi

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a/b=$(($a/$b))"
echo "a%b=$(($a%$b))"
echo "a**b=$(($a**$b))"
运行shell脚本提示“语法错误: 未预期的文件结尾”_shell脚本_03

验证结果:

运行shell脚本提示“语法错误: 未预期的文件结尾”_shell脚本_04

反思总结:

if语句有相应的语法搭配:如  

(1)
if [ command ].... ;then
符合条件执行语句
fi

(2)
if [command]
符合条件执行语句
else
否则执行什么
fi
(3)
if [command];then
符合条件执行语句
elif [command];then
如果符合这个条件,则执行语句
else
否则执行这个语句
fi

2.expr用于整数计算

如何expr 1+b,因为b不是整数,所以相加后运行结果就会出现错误,执行结果返回不是0.

根据执行成功返回结果是0进行判断 1和输入的传参变量是否是整数。

$?  获取执行上一个指令的执行状态返回值,0为成功,非零失败。

慢慢与你并肩


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK