0

我正在创建一个做一些简单数学运算但无法运行的小程序。它只是输出“文件意外结束”。我似乎找不到错误..?

#!/bin/bash

until [ $second_num -ne 0 ]; do
    echo "Enter number 1:"
    read first_num
    echo "Enter number 2:"
    read second_num
    echo "Cannot divide by 0. Start over."
done

result=0
if [ $first_num -ne 999 && $second_num -ne 999 ]; then
    let result=$((first_num/second_num))
    echo $result    
    echo "Program finished!"
else
    echo "You have exited the program."
    exit 0 
fi  

number=1
while [ $number -lt 100 ]; do
    echo $number
    let number=$(( $number % 5 ))
    echo $number >> sample.txt
done
4

3 回答 3

2

乍一看,我发现您的脚本存在 2 个问题:

  • until [ $second_num -ne 0 ]; do

    您没有初始化$second_num,因此您试图将 0 与无进行比较。

  • if [ $first_num -ne 999 && $second_num -ne 999 ]; then

    &&是一个条件执行运算符。(单个)方括号内的两个表达式的 AND 运算符是-a.

于 2013-03-30T21:42:59.637 回答
1

我不知道您要做什么,但是以下代码应该可以正常工作而不会出现任何错误

 #!/bin/bash

until [ $second_num -ne 0 ]; do
    echo "Enter number 1:"
    read first_num
    echo "Enter number 2:"
    read second_num
    echo "Cannot divide by 0. Start over."
done

result=0
if [ "$first_num" -ne "999" -a "$second_num" -ne "999" ];

then
    let result=$(($first_num/$second_num))
    echo $result    
    echo "Program finished!"
else
    echo "You have exited the program."
    exit 0
fi

number=1
while [ $number -lt 100 ]; do
    echo $number
    let number=$(( $number % 5 ))
    echo $number >> sample.txt
done
于 2013-03-30T22:11:20.877 回答
0

我在 bash 版本 4 下执行,没有问题(没有语法错误),但是有些语义错误,变量 second_num 未定义,并且 if 语句第 3 行中的 &&:[:-ne:一元运算符预期输入数字 1:34 输入数字 2:54不能除以 0。重新开始。第 12 行:[:missing `]' 你已经退出了程序。

再次向您发送脚本

于 2013-03-31T10:46:48.673 回答